使用的是Servlet 3.0 新的特征标注(Annotaion)类描述部署,一些低版本的服务器需要使用标准依赖部署描述文件(web.xml)来部署,另外Part也是Java EE 6.0新增的类,Part是一个接口继承于javax.servlet.http,代表一部分表单项目接收来自multipart/form-data的POST的请求。
!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>上传文件</title> </head> <body> <div class="container"> <form action="upload.do" method="post" enctype="multipart/form-data"> <table> <tr> <td><label for="file">上传文件:</label></td> <td><input type="file" id="file" name="picture" value=""/></td> </tr> <tr> <td colspan="2"><input type="submit" value="提交"/></td> </tr> </table> </form> </div> </body> </html>
@MultipartConfig @WebServlet(name = "UploadServlet", urlPatterns = {"/upload.do"}) public class UploadServlet extends HttpServlet { private String contextPath; @Override public void init() throws ServletException { contextPath = getServletContext().getRealPath("/"); } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); Part part = request.getPart("picture"); String fileName = getFileName(part); writeTo(fileName, part); //forward到显示 request.setAttribute("fileName", fileName); request.getRequestDispatcher("show.jsp").forward(request, response); } //取得上传文件名 private String getFileName(Part part) { String header = part.getHeader("Content-Disposition"); String fileName = header.substring(header.indexOf("filename="") + 10, header.lastIndexOf(""")); return fileName; } //存储文件 private void writeTo(String fileName, Part part) throws IOException, FileNotFoundException { InputStream in = part.getInputStream(); OutputStream out = new FileOutputStream(contextPath + fileName); byte[] buffer = new byte[1024]; int length = -1; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } in.close(); out.close(); } }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>图片显示</h1> <a href="${fileName}">${fileName}</a> </body> </html>