SpringBoot中,文件上传与下载的代码,整理如下:
1. 上传:
@PostMapping("/upload")
public String upload(@RequestParam("filebody") MultipartFile file) {
try {
String fileUploadPath = "D:\\....";
File uploadedFile = new File(fileUploadPath, file.getOriginalFilename());
uploadedFile.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(uploadedFile);
fileOutputStream.write(file.getBytes());
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
return "error:" + e.getMessage();
}
return "ok";
}
2. 下载:
@GetMapping("/download/{id}") //ResponseEntity<Resource>
public Object download(@PathVariable("id") Long id) {
//...
String fileName = "xxxx.jpg";
File file = new File("D:\\xxxx.jpg");
try {
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok()
.header("Content-disposition","attachment;filename=" + fileName)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(resource);
}catch(Exception e) {
e.printStackTrace();
return ResponseEntity.status(500).body(e.getMessage());
}
}
总体来说挺简单,代码量也不大。