Spring Boot controller - Upload Multipart and JSON to DTO

前端 未结 8 1139
南旧
南旧 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条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 05:22

    I had a similar use case where I had some JSON data and image upload (Think of it as a user trying to register with a personal details and profile image).

    Referring to @Stephan and @GSSwain answer I came up with a solution with Spring Boot and AngularJs.

    Below is a snapshot of my code. Hope it helps someone.

        var url = "https://abcd.com/upload";
        var config = {
            headers : {
                'Content-Type': undefined
            }
    
        }
        var data = {
            name: $scope.name,
            email: $scope.email
        }
        $scope.fd.append("obj", new Blob([JSON.stringify(data)], {
                    type: "application/json"
                }));
    
        $http.post(
            url, $scope.fd,config
        )
            .then(function (response) {
                console.log("success", response)
                // This function handles success
    
            }, function (response) {
                console.log("error", response)
                // this function handles error
    
            });
    

    And SpringBoot controller:

    @RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = {   "multipart/form-data" })
    @ResponseBody
    public boolean uploadImage(@RequestPart("obj") YourDTO dto, @RequestPart("file") MultipartFile file) {
        // your logic
        return true;
    }
    

提交回复
热议问题