Spring REST没有从MultiPartHttpServletRequest获取文件

时间:2016-06-28 09:05:22

标签: javascript angularjs spring multipartform-data

我正在尝试通过Angular 1.5将文件上传到Spring REST端点。

我没有收到任何错误,因为multiPartRequest.getFileNames();返回null。但是我的JS POST似乎正确地通过了请求。

然而,我似乎无法解决这个问题。我一直在盯着它看几个小时,需要有人指出我错过的显而易见的事情。

任何帮助,建议表示赞赏。

POST请求示例:

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:50188
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryIPlVKLnf1ZIQNPHV
Host:localhost:8080
Origin:http://127.0.0.1:49693
Referer:http://127.0.0.1:49693/test.html
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
Request Payload
------WebKitFormBoundaryIPlVKLnf1ZIQNPHV
Content-Disposition: form-data; name="file"; filename="post-image1.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryIPlVKLnf1ZIQNPHV--
Name

我正在使用以下HTML

                <form enctype="multipart/form-data">                     
                        <input type="file" name="file" onchange="angular.element(this).scope().upload(this.files)"/>
                        <button type="submit">Upload</button>
                        <li ng-repeat="file in files">{{file.name}}</li>
                </form>

随后的JS

$scope.upload = function(files) {
            var fd = new FormData();
            //Take the first selected file
            fd.append("file", files[0]);

            $http.post('uploadURL', fd, {
                withCredentials: true,
                headers: {'Content-Type': undefined },
                transformRequest: angular.identity
            })
             .success(function(d) {
                     console.log("Upload complete" +d);
            })

        };

以下REST端点

@RequestMapping(value="/upload", method=RequestMethod.POST)
    public String upload (HttpServletResponse response, HttpServletRequest request) {

        MultipartHttpServletRequest multiPartRequest = (MultipartHttpServletRequest) request;

        Iterator<String> it = multiPartRequest.getFileNames();
        while (it.hasNext()) {
            MultipartFile multiPartFile = multiPartRequest.getFile(it.next());

            String filename = multiPartFile.getOriginalFilename();
            imageName = filename;

            String path = new File("src/main/resources/images").getAbsolutePath() + "/" + filename;

            try {
                multiPartFile.transferTo(new File(path));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

2 个答案:

答案 0 :(得分:1)

尽量做到这一点

@RequestMapping(value="/upload", method=RequestMethod.POST)
public String upload(MultipartHttpServletRequest request,
        HttpServletResponse response) {
(...)

答案 1 :(得分:0)

我有同样的问题,我通过将<button type="submit">Upload</button>更改为<input type="submit">

来解决此问题