HTTP文件上传原理

  • 2019 年 10 月 3 日
  • 笔记

??

??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????HTTP?????????????????????????????????????????????????????????????????????????????????????

?????????????????????????????????

HTTP????

?????????????????????????????????????????

  • ???????post?
  • ???????????????<input type="file"/>?
  • ????????enctype="multipart/form-data"?

??????????????????????????????????????????

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  <html>  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  <body>  <form action="<%=request.getContextPath() %>/UploadServletDemo" enctype="multipart/form-data" method="post">      ?????<input type="text" name="username"><br/>      ????1?<input type="file" name="file1"><br/>      ????2?<input type="file" name="file2"><br/>             <input type="submit" value="??">  </form>  </body>  </html>

??????????Servlet?

@WebServlet("/UploadServletDemo")  public class UploadServletDemo extends HttpServlet{      @Override      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {          request.setCharacterEncoding("utf-8");            // ????(POST)??          ServletInputStream in = request.getInputStream();//????????????????????            // ???          InputStreamReader inReaser = new InputStreamReader(in);            // ???          BufferedReader reader = new BufferedReader(inReaser);          String str = null;          while ((str=reader.readLine()) != null){              System.out.println(str);          }      }  }

?????????????Fiddler??????????????Post?????????????????

POST http://localhost:8080/javawebservlet_war/UploadServletDemo HTTP/1.1  Host: localhost:8080  Connection: keep-alive  Content-Length: 446  Cache-Control: max-age=0  Origin: http://localhost:8080  Upgrade-Insecure-Requests: 1  Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryqj67FUBQUHXZj78G  User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3  Referer: http://localhost:8080/javawebservlet_war/  Accept-Encoding: gzip, deflate, br  Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,und;q=0.7,zh-TW;q=0.6  Cookie: JSESSIONID=6BE280EF3CBE213F73430FFDF015DE97    ------WebKitFormBoundaryqj67FUBQUHXZj78G  Content-Disposition: form-data; name="username"    abc  ------WebKitFormBoundaryqj67FUBQUHXZj78G  Content-Disposition: form-data; name="file1"; filename="??1.txt"  Content-Type: text/plain    ABC??1  ------WebKitFormBoundaryqj67FUBQUHXZj78G  Content-Disposition: form-data; name="file2"; filename="??2.txt"  Content-Type: text/plain    BDF??2  ------WebKitFormBoundaryqj67FUBQUHXZj78G--

?????????????HTTP?????????HTTP??????????????????????????????????????

Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryqj67FUBQUHXZj78G??????????boundary???????????????????boundary???????????------FormBoundary????------FormBoundary????????

------FormBoundary  Content-Disposition: form-data; name="param1"    value1  ------FormBoundary

??boundary????????????????????????????????????????????Content-Disposition??????????????????form-data?name?????????????????????????????Content-Type??????????MIME????????????????????????

HTTP???????????????????????????????????????????????????????????????????

????boundary???????--

FileUpload??

?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????Bug?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

??????????FileUploadDemo???????????FileUpload???

FileUpload Demo

??????????Demo?

@WebServlet("/FileUpload")  public class FileUploadDemo extends HttpServlet {      @Override      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {          DiskFileItemFactory fac = new DiskFileItemFactory();          ServletFileUpload upload = new ServletFileUpload(fac);          upload.setFileSizeMax(10 * 1024 * 1024);          upload.setSizeMax(20 * 1024 * 1024);            if (upload.isMultipartContent(request)) {              try {                  List<FileItem> list = upload.parseRequest(request);                  for (FileItem item : list) {                      if (item.isFormField()) {                          String fileName = item.getFieldName();                          String value = item.getString("UTF-8");                          System.out.println(fileName + ":" + value);                      } else {                          String name = item.getName();                          String id = UUID.randomUUID().toString();                          name = id + name;                            String realPath = getServletContext().getRealPath("/upload");                          File file = new File(realPath, name);                          item.write(file);                          item.delete();                        }                  }              } catch (Exception e) {                  e.printStackTrace();              }          } else {              System.out.println("????");          }      }  }

??

???????HTTP?????????????????????????????????

2019?7?31? ?????????