Spring开机大文件上传下载支持
Spring boot large file upload and download support
我有一个 spring 启动 Web 应用程序,它将处理大文件(最大大小为 5g)上传,然后将其保存到 s3。请求和响应可能会持续很长时间。
那么像这样处理上传和下载的最佳做法是什么?下载或上传大文件时如何做好性能以防止我的服务器宕机?
你可以使用multipart/form-data
@RequestMapping(value = "/agency/create", method = RequestMethod.POST, consumes = "multipart/form-data")
public ResponseEntity<List<String>> createAgency(
@RequestParam(value = "username", required = true) String username,
@RequestParam(value = "pic1", required = true)MultipartFile pic1File,
MultipartHttpServletRequest request, ModelAndView modelAndView) {
List<String> requestKeys=new ArrayList<String>();
List<String> originalFileName=new ArrayList<String>();
request.getFileNames().forEachRemaining(requestKeys::add);
for(String multipartFile:requestKeys) {
originalFileName.add(request.getFile(multipartFile).getOriginalFilename());
}
storageService.store(pic1File);
return new ResponseEntity<List<String>>(originalFileName, HttpStatus.CREATED);
}
张贴以防将来有人觉得有用。这适用于 Spring Boot 2.4.2.
的 REST 控制器
Class 注释:
@RestController
@RequestMapping("/api")
方法声明:
@RequestMapping(path = "/file-upload/{depot}/{fileName}", method = {RequestMethod.POST, RequestMethod.PUT})
public ResponseEntity<String> fileUpload(
@PathVariable(name = "depot") String depot,
@PathVariable(name = "fileName") String fileName,
InputStream inputStream,
HttpServletRequest request,
HttpServletResponse response)
以上是 REST 控制器的 Spring 引导配置,适用于我的大型文件上传。关键是直接添加InputStream inputStream。
我有一个 spring 启动 Web 应用程序,它将处理大文件(最大大小为 5g)上传,然后将其保存到 s3。请求和响应可能会持续很长时间。
那么像这样处理上传和下载的最佳做法是什么?下载或上传大文件时如何做好性能以防止我的服务器宕机?
你可以使用multipart/form-data
@RequestMapping(value = "/agency/create", method = RequestMethod.POST, consumes = "multipart/form-data")
public ResponseEntity<List<String>> createAgency(
@RequestParam(value = "username", required = true) String username,
@RequestParam(value = "pic1", required = true)MultipartFile pic1File,
MultipartHttpServletRequest request, ModelAndView modelAndView) {
List<String> requestKeys=new ArrayList<String>();
List<String> originalFileName=new ArrayList<String>();
request.getFileNames().forEachRemaining(requestKeys::add);
for(String multipartFile:requestKeys) {
originalFileName.add(request.getFile(multipartFile).getOriginalFilename());
}
storageService.store(pic1File);
return new ResponseEntity<List<String>>(originalFileName, HttpStatus.CREATED);
}
张贴以防将来有人觉得有用。这适用于 Spring Boot 2.4.2.
的 REST 控制器Class 注释:
@RestController
@RequestMapping("/api")
方法声明:
@RequestMapping(path = "/file-upload/{depot}/{fileName}", method = {RequestMethod.POST, RequestMethod.PUT})
public ResponseEntity<String> fileUpload(
@PathVariable(name = "depot") String depot,
@PathVariable(name = "fileName") String fileName,
InputStream inputStream,
HttpServletRequest request,
HttpServletResponse response)
以上是 REST 控制器的 Spring 引导配置,适用于我的大型文件上传。关键是直接添加InputStream inputStream。