javascript
Spring Boot文档阅读笔记-FileHandling解析及抓包分析
這篇博文將說明使用WEB服務(wù)上傳和下載文件。
首先是文件上傳:
使用MultipartFile作為請(qǐng)求參數(shù),這個(gè)上傳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頭設(shè)置為Content-Disposition,并且還需指定響應(yīng)為流媒體。
完整代碼如下:
@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;}使用如下:
上傳成功后,會(huì)在這個(gè)目錄中存在文件:
項(xiàng)目打包下載地址:
https://github.com/fengfanchen/Java/tree/master/SpringBootFileHandling
?
下面來分析下這個(gè)過程:
使用Fiddler抓包如下:
上傳文件
從中可以看到,content-type為multipart/formdata其中邊界分隔符為后面那個(gè)。他傳的其實(shí)是二進(jìn)制。
content-Disposition為內(nèi)容傾向,為表單數(shù)據(jù),name為程序中需要提交的鍵,filename為文件名。
下面的行,就是文件內(nèi)容了。
?
下面來看看下載:
輸入U(xiǎn)RL會(huì)激活I(lǐng)DM的下載
Fiddler下載如下:
這里的返回為Content-Disposition:為attachment說明是附件以及filename="cff.pdf",很多瀏覽器就是根據(jù)這條來判斷,是文件的。
如果沒有這條,就不會(huì)激發(fā)瀏覽器的下載。
?
?
?
?
總結(jié)
以上是生活随笔為你收集整理的Spring Boot文档阅读笔记-FileHandling解析及抓包分析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android逆向笔记-使用dnSpy修
- 下一篇: Spring Boot笔记-valida