我们把文件的上传与下载定义到common大路由下。当文件上传就会访问/upload的路由中,文件下载时就通过/download路由。

@RestController
@RequestMapping("/common")
public class CommonController {
    // 直接通过transferTo进行保存
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String filePath = "D://" + originalFilename;
        File saveFile = new File(filePath);
        file.transferTo(saveFile);
        return R.success(originalFilename);
    }

		// 通过stream的放入直接写入到response中
    @GetMapping("/download")
    public R<String> download(String name, HttpServletResponse response) throws IOException {
        String filePath = "D://" + name;
        FileInputStream fileInputStream = new FileInputStream(filePath);

        ServletOutputStream outputStream =  response.getOutputStream();
        int len = 0;
        byte[] bytes = new byte[1024];
        while( (len = fileInputStream.read(bytes)) != -1){
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }
        return R.success("下载成功");
    }
}