java - spring mvc 中包含多部分数据的 POST 请求

标签 java angularjs spring-mvc cors ng-file-upload

我正在使用 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/

相关文章:

java - 对非静态方法的静态引用(在主方法中)

java - 扩大原始转换文献

javascript - ng-click 和子选择器

angularjs - angularjs Material Design 中的对话框弹出窗口如何返回 promise ?

javascript - 如何在内容加载完成时停止 ui-grid 的无限滚动?

java - 如何将任何路径级别的扩展与 Spring MVC 匹配?

java - Spring 3 未找到 HTTP 请求的映射 初学者

java - 使用spring实现登录检查

java - BufferedImage 图像指针数据作为 C 函数的 JNI 参数

Java 小服务程序 : How to share common behaviour among multiple servlets?