Search code examples
spring-bootinputstreamputmultiparthttp-method

400 BAD Request error on HttpMethod.PUT - File upload second time


I have a PUT request method in the controller where I upload zip file and the method takes it as inputstream and processes the stream. It works well with file sizes of Kb. Now I uploaded a zip file of 10Mb size, and it works fine the first time. The second time, it doesn't upload and I get the BAD request error. When I restart the service, it works fine for the first time and the second time I receive the same BAD Request 400 error. Pease advise

@RequestMapping(path = “/upload/{fileName}”, method = PUT,
    consumes = "multipart/form-data", produces = "application/json; charset=UTF-8")

 public void upload(@PathVariable(“fileName”) String fileName,
            @RequestBody MultipartFile[] multipartFile) throws IOException{ 

        //inputstream is processed here

    }

Solution

  • To upload a file in spring boot i prefere this approache :

    @RequestMapping(value = "/upload", method = RequestMethod.PUT) // Or POST
    @ResponseStatus(HttpStatus.OK)
    public void upload(@RequestParam("file") MultipartFile file) {
    
        System.out.println(String.format("File name %s", file.getName()));
        System.out.println(String.format("File original name %s", file.getOriginalFilename()));
        System.out.println(String.format("File size %s", file.getSize()));
    
        //do whatever you want with the MultipartFile
        file.getInputStream();
    }
    

    Configuring Multipart File Uploads in Spring Boot

    The most used properties are:

    1. spring.http.multipart.file-size-threshold: A threshold after which the files are written to disk. Supports MB or KB as suffixes to indicate size in Megabyte or Kilobyte

    2. spring.http.multipart.location: location of the temporary files

    3. spring.http.multipart.max-file-size: Max size per file the upload supports; also supports the MB or KB suffixes; by default 1MB

    4. spring.http.multipart.max-request-size: max size of the whole request; also supports the MB or KB suffixes

    You can of course change these config in your application.properties of yml.

    In your case i prefere that you go to your rest api and you check the stack error to see what is the exacte error.