javascript
Spring Boot文档阅读笔记-FileHandling解析及抓包分析
這篇博文將說明使用WEB服務上傳和下載文件。
首先是文件上傳:
使用MultipartFile作為請求參數,這個上傳API使用Multi-Part表單的值:
代碼如下:
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)public String fileUpload(@RequestParam("file")MultipartFile file) throws IOException {File convertFile = new File("./" + file.getOriginalFilename());convertFile.createNewFile();FileOutputStream fout = new FileOutputStream(convertFile);fout.write(file.getBytes());fout.close();return "File is upload successfully";}下面是文件下載:
使用InputStreamResource獲取需要下載的文件,然后將http頭設置為Content-Disposition,并且還需指定響應為流媒體。
完整代碼如下:
@GetMapping(value = "/download")public ResponseEntity<Object> download(@RequestParam("fileName") String fileName) throws FileNotFoundException {File file = new File(fileName);InputStreamResource inputStreamResource = new InputStreamResource(new FileInputStream(file));HttpHeaders httpHeaders = new HttpHeaders();httpHeaders.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));httpHeaders.add("Cache-Control", "no-cache, no-store, must-revalidate");httpHeaders.add("Pragma", "no-cache");httpHeaders.add("Expires", "0");ResponseEntity<Object> responseEntity = ResponseEntity.ok().headers(httpHeaders).contentLength(file.length()).contentType(MediaType.parseMediaType("application/txt")).body(inputStreamResource);return responseEntity;}使用如下:
上傳成功后,會在這個目錄中存在文件:
項目打包下載地址:
https://github.com/fengfanchen/Java/tree/master/SpringBootFileHandling
?
下面來分析下這個過程:
使用Fiddler抓包如下:
上傳文件
從中可以看到,content-type為multipart/formdata其中邊界分隔符為后面那個。他傳的其實是二進制。
content-Disposition為內容傾向,為表單數據,name為程序中需要提交的鍵,filename為文件名。
下面的行,就是文件內容了。
?
下面來看看下載:
輸入URL會激活IDM的下載
Fiddler下載如下:
這里的返回為Content-Disposition:為attachment說明是附件以及filename="cff.pdf",很多瀏覽器就是根據這條來判斷,是文件的。
如果沒有這條,就不會激發瀏覽器的下載。
?
?
?
?
總結
以上是生活随笔為你收集整理的Spring Boot文档阅读笔记-FileHandling解析及抓包分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android逆向笔记-使用dnSpy修
- 下一篇: 信息安全工程师笔记-网络安全风险评估技术