1、上传文件
@RestController
@RequestMapping("/file")
public class FileUploadController {
/**
* 对于上载文件,要将MultipartFile用作请求参数,
* @param file
* @return
* @throws IOException
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String fileUpload(@RequestParam("file") MultipartFile file) throws IOException {
// 上传的路径
File convertFile = new File("/home/user/temp/"+file.getOriginalFilename());
convertFile.createNewFile();
FileOutputStream fout = new FileOutputStream(convertFile);
fout.write(file.getBytes());
fout.close();
return "File is upload successfully";
}
}
2、下载文件
/**
* 对于文件下载,应该使用InputStreamResource下载文件。
* 需要在Response中设置HttpHeader Content-Disposition,并且需要指定应用程序的响应Media Type。
* @return
* @throws IOException
*/
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<Object> downloadFile() throws IOException {
// 下载的目标文件
String filename = "/home/user/temp/exceldata.png";
File file = new File(filename);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
ResponseEntity<Object>
responseEntity = ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(
MediaType.parseMediaType("application/txt")).body(resource);
return responseEntity;
}
3、测试
- 上传
a、设置POST请求,Header的Content-Type为multipart/form-data
b、设置Body为form-data,然后添加File类型的key:file,选择要上传的文件
c、发送请求--返回"File is upload successfully"
- 下载