我正在使用 ng-file-upload在客户端的 Angular 中将文件(图像、文本等)发送到 Spring Boot 应用程序。
我在 Xampp 中使用 url“localhost”运行客户端,同时使用 url“localhost:8080”单独运行 spring 实例。双方都启用了 cors,其他所有请求都已成功受理。
客户端代码:
Upload.upload({
url: 'http://localhost:8080/file/upload',
method:'POST',
data: {
uploadedPicture: file,
uploadedFrom: 'recipe'
},
}).then(function(response) {
$timeout(function() {
$scope.result = response.data;
});
}, function(response) {
if (response.status > 0) $scope.errorMsg = response.status + ': ' + response.data;
}, function(evt) {
$scope.progress = parseInt(100.0 * evt.loaded / evt.total);
});
服务器端代码:
@CrossOrigin
@RequestMapping(method = RequestMethod.POST, value = "/file/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (!file.isEmpty()) {
try {
Files.copy(file.getInputStream(), Paths.get(ROOT, file.getOriginalFilename()));
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
} catch (IOException|RuntimeException e) {
redirectAttributes.addFlashAttribute("message", "Failued to upload " + file.getOriginalFilename() + " => " + e.getMessage());
}
} else {
redirectAttributes.addFlashAttribute("message", "Failed to upload " + file.getOriginalFilename() + " because it was empty");
}
return "redirect:/";
}
我已经尝试通过使用 get 方法从相同代码向相同资源发送 get 请求来尝试 cors。但是当我发送带有多部分表单数据(图像或任何其他文件)的 post 请求时,它拒绝 OPTIONS 请求。
OPTIONS http://localhost:8080/file/upload
XMLHttpRequest cannot load http://localhost:8080/file/upload. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 403.
我也通过 postman 测试了这个资源,它上传文件没有错误。
编辑: 我已经尝试将 http 更改为 https,它给出的错误是 OPTIONS https://localhost:8080/file/upload net::ERR_TIMED_OUT_ 问题与找不到所需资源相同
对这个问题有什么想法吗??
最佳答案
查看您的错误消息,我看到了:
No 'Access-Control-Allow-Origin' header is present
您确定添加了正确的 header 吗?
我们使用过滤器来确保所有请求都正确添加了这些 header :
- 访问控制允许来源:*
- 访问控制允许方法:POST、GET、OPTIONS、DELETE
- 访问控制最大年龄:3600
- 访问控制允许 header :x-requested-with
这是我们使用的 Filter 类:
SimpleCORSFilter.java
@Component
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
关于java - spring mvc 中包含多部分数据的 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39190436/