javaspring-bootmultipart

Is it possible to get both Multipart file and a RequestBody in springboot?


I want to have a post method in Springboot which will post data to database where I've a table which holds data of an employee and that includes resume as well. I want to have resume as a document hence I had byte[] on the entity class. I passed the document as Multipart/form-data from the postman and had the requestBody in the raw body section as JSON data. But couldn't do so.

I passed the document as Multipart/form-data from the postman and had the requestBody in the raw body section as JSON data with the controller written like,

@PostMapping()
public ResponseEntity<EmployeeMinimalResponseDTO> postEmployee(
            @RequestPart(value = "resume") MultipartFile file,
            @RequestBody(required = false) EmployeeDTO employeeDTO) throws IOException {
     Employee employee = Converters.getEmployeeFromEmployeeDto(employeeDTO);
     employee.setResume(file.getBytes());
     return this.employeeService.postEmployee(employee);
}

leads to an Internal Server Error saying 'Current request is not a multipart request'. What am I doing wrong ? Do I have to do any kind of configuration to make it work. I had [starter web, Data JPA, mysql Connector, Lombok] dependencies.

Here is my Application.properties,

spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=2KB
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=7MB

followed by mysql configuration.

But, I had a controller to check the Multipart upload alone and that works fine like,

@PostMapping("check")
    public String fileUploadCheck(@RequestPart(value = "resume",required = false) MultipartFile file) throws IOException{
        Employee employee= new Employee();
        employee.setResume(file.getBytes());
        this.employeeService.postEmployee(employee);
        return "file uploaded successfullly..";
    }

which happily returns, "file uploaded successfullly.." I don't know why. Can anyone help me on this. Thanks in advance :)


Solution

  • Use @RequestPart, Here is an example.

    save(@RequestPart(value = "file1", required = false) MultipartFile file1,
    @RequestPart(value = "file2", required = false) MultipartFile file2,
    @RequestPart MyDto myDto)
          
    

    in your frontend

    let formData = new FormData();
    formData.append('file1', this.myForm.get('file1')?.value);
    formData.append('MyDto', new Blob([JSON
          .stringify(MyModlel)], {
          type: 'application/json'
    }));