【问题标题】:Spring AngularJS upload file functionality - 400 error Bad requestSpring AngularJS上传文件功能 - 400错误错误请求
【发布时间】:2016-03-23 00:58:19
【问题描述】:

我正在尝试使用 Spring 和 AngularJS 上传文件,但收到 400 Bad request 错误:

> error: "Bad Request"
> exception: "org.springframework.web.multipart.support.MissingServletRequestPartException"
> message: "Required request part 'file' is not present."
> path:"/project/ffl/newDocument

我经历了如何实现功能的不同示例(#1#2#3#4#5 等等)并遵循了所有这些示例。虽然,我仍然收到 400 错误。

我的要求:

Request URL:https://localhost:8443/project/ffl/newDocument
Request Method:POST
Status Code:400 Bad Request
Remote Address:[::1]:8443
Response Headers
view source
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Connection:close
Content-Type:application/json;charset=UTF-8
Date:Wed, 16 Dec 2015 18:24:08 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
Strict-Transport-Security:max-age=31536000 ; includeSubDomains
Transfer-Encoding:chunked
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block

Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8,uk;q=0.6,ru;q=0.4
Connection:keep-alive
Content-Length:75515
Content-Type:multipart/form-data; boundary=----WebKitFormBoundarylcovac73AQDt1CNW
Host:localhost:8443
Origin:https://localhost:8443
Referer:https://localhost:8443/project/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36
X-Requested-With:XMLHttpRequest

Request Payload
------WebKitFormBoundarylcovac73AQDt1CNW
Content-Disposition: form-data; name="file"; filename="test.pdf"
Content-Type: application/pdf


------WebKitFormBoundarylcovac73AQDt1CNW--

HTML:

<form ng-submit="uploadFile()" class="form-horizontal" enctype="multipart/form-data">
   <input type="file" name="file" id="file" ng-model="document.fileInput" onchange="angular.element(this).scope().upload(this)" >
   <button class="btn btn-primary" type="submit">Submit</button>
</form>

JS:

    $scope.document = {};
      var file = {};
      $scope.upload = function(fileInput) {
        file = fileInput;
      };

  $scope.uploadFile = function(){
    var formData = new FormData();
    formData.append("file", file.files[0]);

    $http.post('ffl/newDocument', formData, {
       headers: {'Content-Type': undefined },
       transformRequest: angular.identity
            }).then(function (response) {

            }, function (error) {
                console.error('Error: ', error.status, error.data);
                });
       };

Java:

@RestController
@RequestMapping("/ffl")

@RequestMapping(value="/newDocument", method = RequestMethod.POST, consumes = {"multipart/form-data"})
public @ResponseBody void uploadFile(@RequestPart("file") MultipartFile file) throws IOException {

我们将不胜感激。

【问题讨论】:

  • 您是否看到任何日志错误/mgs?
  • Rossi,我在浏览器控制台中只看到 400 错误消息。我的 Eclipse 控制台中没有任何内容。

标签: javascript java angularjs spring spring-mvc


【解决方案1】:

1。列表项 更改 Spring Controller 上的方法以使用它:

    RequestMapping(value = "/newDocument", method = RequestMethod.POST)
    public @ResponseBody Object uploadFiles(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException {
        
        Iterator<String> iterator = request.getFileNames();
        MultipartFile multipartFile = null;
        while (iterator.hasNext()) {
            multipartFile = request.getFile(iterator.next());
            //do something with the file.....
        }
    } 

2。还有你的 Angular 控制器:

    console.log(files[0]);
    $http.post( '/myEndpoint', formData, {
        headers: { 'Content-Type': undefined },
        transformRequest: angular.identity
    }).success(function (result) {
        console.log('Success');
    }).error(function () {
        console.log('Failure');
    });  

3。你应该有以下依赖:

commons-fileupload

4。在你的 servlet-configuration.xml 中添加这个 bean

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

【讨论】:

  • 感谢您的建议,但没有奏效。我能够点击我的 spring 控制器,但是请求为空并且 while 循环没有执行,因为迭代器中没有任何内容。
  • 您的文件数组中有文件吗?您可以使用浏览器调试器 (F12) 并验证。
  • 是的,在将请求发送到后端之前,我在 files 数组中看到了我的文件。
  • 尝试使用不同的文件上传。
  • 我在 html 上添加了 3 个输入、3 个相应的 js 函数和 3 个附加到我的 FormData 对象。我上传了一个 pdf、一个 zip 和一个 txt 文件,但在 spring 控制器中,请求保持为空。我在调用后端之前检查了调试器中的文件并且文件在那里。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
相关资源
最近更新 更多