springboot 文件上传下载

关键点:

1,使用 POST 请求
2,consumes=MediaType.MULTIPART_FROM_DATA_VALUE
3,@RequestParm 里面的字符串和前端 input 控件的 name 值一致

上传文件示例:

@PostMapping(value="/photos", consumes=MediaType.MULTIPART_FROM_DATA_VALUE)
public void addPhoto(@RequestParm("photo") MultipartFile imgFile) throws Exception{
    // 保存文件
    FileOutputStream fos = new FileOutputStream("target/", imgFile.getOriginalFilename());
    IOUtils.copy(imgFile.getInputStream(), fos);
    fos.close();
  
}

带返回值上传文件示例(返回二进制数据,让用户看到上传的图片长什么样):

@PostMapping(value="/icon", consumes=MediaType.MULTIPART_FROM_DATA_VALUE)
public Byte[] addIcon(@RequestParm("photo") MultipartFile imgFile) throws Exception{
     // 用户上传文件的二进制数据
     InputStream is = imgFile.getInputStream();
     // 保存文件
     FileOutputStream fos = new FileOutputStream(new File("F:" + File.separator + imgFile.getOriginalFilename()));
     IOUtils.copy(is, fos);
     fos.close();
     // 返回文件
     return IOUtils.toByteArray(is);
    }

下载文件示例:

@GetMapping(value="/{userId}/photos", consumes=MediaType.MULTIPART_FROM_DATA_VALUE)
public void getPhoto(@RequestParm("photo") MultipartFile imgFile) throws Exception{
       // 返回文件
       String userPhotoImgSrc = "src/test/10001.jpg";
       InputStream is = new FileInputStream(userPhotoImgSrc);
       return IOUtils.toByteArray(is);
}
原文地址:https://www.cnblogs.com/huanggy/p/9471845.html