aisensiy
aisensiy

Reputation: 1520

Spring boot large file upload and download support

I have a spring boot web application which will handle large file (max size of 5g) upload and then save it to s3. The request and response may last for a long time.

So what is the best practice to handle the upload and download like this? How to make a good performance to prevent my server down when download or upload large files?

Upvotes: 2

Views: 4918

Answers (2)

Will Iverson
Will Iverson

Reputation: 2069

Posting in case someone finds this useful in the future. This works with a REST controller as of Spring Boot 2.4.2.

Class annotations:

@RestController
@RequestMapping("/api")

Method declaration:

@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)

The above is the Spring Boot configuration for a REST Controller that worked for me for large file upload. The key was adding InputStream inputStream directly.

Upvotes: 0

Pedram Ezzati
Pedram Ezzati

Reputation: 325

you can use 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);
    }

Upvotes: 1

Related Questions