Spring boot文件上傳

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

文件上傳

application.properties

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

參考

相關文章
相關標籤/搜索