欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring boot文件上传

程序员文章站 2022-05-04 09:52:58
...

Spring boot

import org.apache.commons.lang3.RandomStringUtils;
@Controller
public class FileUploadController {

@PostMapping("/updateFile")
  public ResponseEntity updateFile(HttpServletRequest servletRequest,
      @ApiParam(value = "multipart/form-data方式上传文件", required = true) @RequestParam("file") MultipartFile file) {
	  File directory = new File(servletRequest.getServletContext().getRealPath("/image"));
    if (!directory.exists()){
      directory.mkdirs();
    }
    File dest = new File(directory.getAbsolutePath(),String.format("%s_%s",RandomStringUtils.randomAlphabetic(10), file.getOriginalFilename()));
    try {
      file.transferTo(dest);
      //...
    } catch (Exception e) {
      e.printStackTrace();
      // 上传异常
      throw new HandleException(String.format("文件上传失败[%s]", e.getMessage()));
    } finally {
     // ...
    }
  }
}

PostMan

Spring boot文件上传

application.properties

# MULTIPART (MultipartProperties)
spring.servlet.multipart.max-file-size=1GB
spring.servlet.multipart.max-request-size=10GB

参考

转载于:https://my.oschina.net/fxtxz2/blog/3018833