Spring 梳理-處理Multipart 請求
阿新 • • 發佈:2018-11-10
- 原理講解
-
簡單的HTTP POST 大家通過HTTP向伺服器傳送POST請求提交資料,都是通過form表單提交的,程式碼如下: <form method="post"action="http://w.sohu.com" > <inputtype="text" name="txt1"> <inputtype="text" name="txt2"> </form> 提交時會向伺服器端發出這樣的資料(已經去除部分不相關的頭資訊),資料如下: POST / HTTP/1.1
-
- 後臺處理
- 使用multipart/form-data提交的資料使用HttpServletRequest物件的getParameter()等方法無法讀取。可以讀取整個請求體資料流自己解析資料。但更好的方式是使用已經有的第三方工具類,如fileupload,jspsmartupload。下面的例子中使用的是fileupload。
-
HttpServletRequeest request=.... if(ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); for(FileItem i: items) { i.getFieldName(); //引數名 //i.getString(); //引數值(返回字串),如果是上傳檔案,則為檔案內容 //i.get(); //引數值(返回位元組陣列),如果是上傳檔案,則為檔案內容 //i.getSize(); //引數值的位元組大小 //i.getName(); //上傳檔案的檔名 //i.getContentType(); //上傳檔案的內容型別 if(!i.isFormField()&&i.getSize()>0) //簡單引數返回true,檔案返回false Files.write(Paths.get("/upload/"+Paths.get(i.getName()).getFileName()), i.get()); } }