一、http的四種請求參數
http四種請求參數方式:即form-data、x-www-form-urlencoded、raw、binary
1,form-data
http請求中的multipart/form-data,它會將表單的數據處理為一條消息,以標簽為單元,用分隔符分開。既可以上傳鍵值對,也可以上傳文件。當上傳的字段是文件時,會有Content-Type來說明文件類型;content-disposition,用來說明字段的一些信息;由於有boundary隔離,所以multipart/form-data既可以上傳文件,也可以上傳鍵值對,它采用了鍵值對的方式,所以可以上傳多個文件。
2,x-www-form-urlencoded
就是application/x-www-from-urlencoded,會將表單內的數據轉換為鍵值對,比如,name=java&age = 23
3,raw
可以上傳任意格式的文本,可以上傳text、json、xml、html等
4,binary
相當於Content-Type:application/octet-stream,從字面意思得知,只可以上傳二進制數據,通常用來上傳文件,由於沒有鍵值,所以,一次只能上傳一個文件。如果想要同時傳文件名,可以借用請求頭“Content-Disposition”,設置文件名。
二、http三種上傳方式
http三種上傳方式:根據上述四種參數請求方式,其中urlencoded只能傳輸文本,因此http只有三種文件上傳方式,form-data、raw、binary
1,針對form-data上傳,springMVC后端接收寫法
1 @RequestMapping(value="/upload", method = RequestMethod.POST) 2 public ResponseObject<?> upload(@RequestParam(value="file", required = true)MultipartFile file,HttpServletRequest request){ 3 String destination = "/filePath/" + multipartFile.getOriginalFilename(); 4 File file = new File(destination); 5 multipartFile.transferTo(file); 6 }
2,針對raw與binary方式上傳,servlet后端接收寫法
1 @RequestMapping(value = "/upload", method = RequestMethod.POST) 2 public ResponseObject<?> upload(MultipartFile multipartFile, HttpServletRequest request) { 3 try { 4 InputStream in = request.getInputStream(); 5 String disposition = request.getHeader("Content-Disposition"); 6 String fileName = null; 7 if (disposition != null && disposition.length() > 0) { 8 fileName = disposition.replaceFirst("(?i)^.*filename=\"?([^\"]+)\"?.*$", "$1"); 9 } 10 if (fileName == null || fileName.length() <= 0) 11 fileName = new String("d:\\abcdef.xed"); 12 FileOutputStream fos = new FileOutputStream(fileName); 13 byte[] b = new byte[1024]; 14 int length; 15 while ((length = in.read(b)) > 0) { 16 fos.write(b, 0, length); 17 } 18 in.close(); 19 fos.close(); 20 } catch (Exception e) { 21 logger.error("file upload error", e); 22 } 23 }