使用AngularJS和Spring MVC上传文件和表单数据

时间:2018-07-09 05:04:51

标签: angularjs spring spring-mvc xmlhttprequest multipartform-data

我正在尝试使用$ http从AngularJS上传带有其他表单数据的文件到Spring MVC控制器。我收到此错误:

HTTP Status 400 - Required request part 'file' is not present
The request sent by the client was syntactically incorrect.

以下是发送AngularJS请求的post代码:

service.create = function(id, photo) {
            var formData = new FormData();
            formData.append('name', photo.name);
            formData.append('file', photo.file);
            formData.append('story', photo.story);
            if (!photo.url) {
                photo.url = null;
            }
            formData.append('url', photo.url);
            return $http(
                    {
                        method : 'POST',
                        transformRequest: angular.identity,
                        transformResponse: angular.identity,
                        url : BASE_URL + authService.getToken().id
                                + '/resource/' + id + '/photo/',
                        data : formData,
                        headers : {
                            'Content-Type' : undefined
                        }
                    }).then(function(res) {
                return res;
            });
        };

这是我的Spring MVC controller方法接收请求:

@Override
@RequestMapping(path = "user/{uid}/resource/{lid}/photo", method = RequestMethod.POST)
public Photo create(HttpServletRequest request, HttpServletResponse response, @PathVariable int uid, @PathVariable int lid,
        @RequestParam MultipartFile file, @RequestParam String name, @RequestParam String url, @RequestParam String story) {
    return photoDAO.create(uid, lid, file, name, url, story);
}

我还将MultipartResolver bean添加到了我的配置中:

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="10000000" />
</bean>

是什么导致控制器找不到file请求参数?我还应该如何读取文件才能将其作为MultipartFile

注意:我知道还有许多其他问题与我的问题类似。那里的答案都没有帮助我。


文件正在作为有效内容的一部分发送。这是有效负载的样子:

------WebKitFormBoundaryK0onA6CrI1KaKcJY Content-Disposition: form-data; name="name" 
n 
------WebKitFormBoundaryK0onA6CrI1KaKcJY Content-Disposition: form-data; name="file" 
PNG [REMOVED FOR SPACE] % V4¡´ºÝÝ6nI6Ú"èdöîÎÉÎ83»ý¡OEP|1êÄ¿· (õÛ>´/ 
------WebKitFormBoundaryK0onA6CrI1KaKcJY Content-Disposition: form-data; name="story" 
st 
------WebKitFormBoundaryK0onA6CrI1KaKcJY Content-Disposition: form-data; name="url" 
null 
------WebKitFormBoundaryK0onA6CrI1KaKcJY--

0 个答案:

没有答案