Servlet3.0新特性之---文件上传API一、文件上传方法 Servlet3.0改进了文件上传API,主要是通过以下方法来实现的: Part getPart(String name) 根据名称获取文件上传域; Collection<Part> getParts() 获取所有文件上传域 二、文件上传表单设置 表单提交方式必须设置成post;表单的enctype必须设置成:multipart/form-data; 【文件上传表单】 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <h1>Servlet3.0文件上传</h1> 9 <form action="/uploadFileUpload" method="post" enctype="multipart/form-data"> 10 文件:<input type="file" name="file"><br> 11 <input type="submit" value="提交"> 12 </form> 13 </body> 14 </html> 三、文件上传后台实现 上传文件的Servlet需要加上@MultipartConfig注解 1 package com.heima.servlet; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.MultipartConfig; 5 import javax.servlet.annotation.WebServlet; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import javax.servlet.http.Part; 10 import java.io.IOException; 11 12 /** 13 * @author buguniao 14 * @date 2018-06-25 11:13 15 */ 16 @WebServlet(name = "FileUploadServlet",urlPatterns = "/uploadFileUpload") 17 @MultipartConfig 18 public class FileUploadServlet extends HttpServlet{ 19 @Override 20 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 21 doPost(req,resp); 22 } 23 24 @Override 25 protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException { 26 //获得Par对象(每个Part对象对应一个文件域) 27 Part part = request.getPart("file"); 28 //获取上传文件大小 29 long size = part.getSize(); 30 //获得包含原始文件名的字符串 31 String info = part.getHeader("content-disposition"); 32 //获取原始文件名 33 String fileName = info.substring(info.indexOf("filename=\"")+10,info.length()-1); 34 //将文件上传到某个位置 35 part.write(getServletContext().getRealPath("uploadFiles")+"/"+fileName); 36 } 37 }
|