这篇博文将说明使用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",很多浏览器就是根据这条来判断,是文件的。
如果没有这条,就不会激发浏览器的下载。