Spring Boot controller - Upload Multipart and JSON to DTO

前端 未结 8 1140
南旧
南旧 2020-11-28 05:16

I want to upload a file inside a form to a Spring Boot API endpoint.

The UI is written in React:

export function createExpense(formData) {
  return         


        
8条回答
  •  旧时难觅i
    2020-11-28 05:40

    I built my most recent file upload application in AngularJS and SpringBoot which are similar enough in syntax to help you here.

    My client side request handler:

    uploadFile=function(fileData){
        var formData=new FormData();
        formData.append('file',fileData);
        return $http({
            method: 'POST',
            url: '/api/uploadFile',
            data: formData,
            headers:{
                'Content-Type':undefined,
                'Accept':'application/json'
            }
        });
    };
    

    One thing to note is Angular automatically sets the multipart mime type and boundary on the 'Content-Type' header value for me. Yours may not, in which case you need to set it yourself.

    My application expects a JSON response from the server, thus the 'Accept' header.

    You are passing in the FormData object yourself, so you need to make sure that your form is setting the File to whatever attribute you map to on your Controller. In my case it is mapped to the 'file' parameter on the FormData object.

    My controller endpoints look like this:

    @POST
    @RequestMapping("/upload")
    public ResponseEntity upload(@RequestParam("file") MultipartFile file) 
    {
        if (file.isEmpty()) {
            return new ResponseEntity(HttpStatus.BAD_REQUEST);
        } else {
            //...
        }
    }
    
    
    

    You can add as many other @RequestParam as you'd like, including your DTO that represents the rest of the form, just make sure its structured that way as a child of the FormData object.

    The key take-away here is that each @RequestParam is an attribute on the FormData object body payload on the multipart request.

    If I were to modify my code to accommodate your data, it would look something like this:

    uploadFile=function(fileData, otherData){
        var formData=new FormData();
        formData.append('file',fileData);
        formData.append('expenseDto',otherData);
        return $http({
            method: 'POST',
            url: '/api/uploadFile',
            data: formData,
            headers:{
                'Content-Type':undefined,
                'Accept':'application/json'
            }
        });
    };
    

    Then your controller endpoint would look like this:

    @POST
    @RequestMapping("/upload")
    public ResponseEntity upload(@RequestParam("file") MultipartFile file, @RequestParam("expenseDto") ExpensePostDto expenseDto)
    {
        if (file.isEmpty()) {
            return new ResponseEntity(HttpStatus.BAD_REQUEST);
        } else {
            //...
        }
    }
    
        

    提交回复
    热议问题