gpt4 book ai didi

javascript - Spring REST 未从 MultiPartHttpServletRequest 获取文件

转载 作者:行者123 更新时间:2023-11-27 22:50:50 26 4
gpt4 key购买 nike

我正在尝试通过 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;
}

最佳答案

尝试做到这一点

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

关于javascript - Spring REST 未从 MultiPartHttpServletRequest 获取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38071726/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com