【问题标题】:Mixed POST submit from AngularJS to Spring RestController从 AngularJS 到 Spring RestController 的混合 POST 提交
【发布时间】:2015-05-29 18:59:20
【问题描述】:

基本上,我希望能够发布带有一些字段 (JSON) 和附件(多部分)的表单。 以下实际上是工作代码,问题是我不喜欢它,所以它主要是因为变通方法而起作用。

角度控制器

$http({
    method: 'POST',
    url: 'rest/store/logo',
    headers: {'Content-Type': undefined },
    transformRequest: function (data) {
        var formData = new FormData();
        //need to convert our json object to a string version of json otherwise the browser will do a 'toString()' on the object which will result in the value '[Object object]' on the server.
        formData.append("store", angular.toJson(data.store));
        formData.append("file", data.file);
        return formData;
    },
    data: { store: $scope.selectedStore, file: $scope.myFile } //not important but $scope.myFile comes from a directive: http://jsfiddle.net/JeJenny/ZG9re/
});

弹簧控制器

@RequestMapping(value = "/logo", method = RequestMethod.POST)
public @ResponseBody void updateLogo(HttpServletRequest request, @RequestParam(value = "store", required = false) String store, @RequestPart("file") MultipartFile file) {
    System.err.println("store: " + store); //the JSON 
    StoreEditTO storeEditTO = new Gson().fromJson(store, StoreEditTO.class);
    System.err.println("storeEditTO: " + storeEditTO);
}

因此,尽管这可行,但我确信有两件事可以简化:

  1. Angular:还不错,但代码似乎比它应该的复杂得多
  2. 春天:这是最烦人的;文件没问题,但我需要将store 的参数类型设置为String,否则Spring 会给我一个'找不到匹配的编辑器或转换策略'。不知何故,请求参数不被识别为 JSON,我猜这是因为将内容类型设置为未定义但如果我没有得到:'org.springframework.web.multipart.MultipartException:当前请求是不是多部分请求'

顺便说一下,分别发布两者都很好。 JSON 被转换为正确的类型并接收到文件。到目前为止,我已经花了几个小时让混合模式(以一种干净的方式)工作,但没有运气......

【问题讨论】:

标签: json angularjs spring rest multipartform-data


【解决方案1】:

感谢上面提到的评论/链接,我得到了它干净的工作。我实际上已经很接近了,但我错过了{type: "application/json"}

完整的解决方案:

@RequestMapping(value = "/logo", method = RequestMethod.POST, consumes = {"multipart/form-data"})
public @ResponseBody void updateLogo(@RequestPart(value = "store") StoreEditTO store, @RequestPart("file") MultipartFile file) {
}

$http({
    method: 'POST',
    url: 'rest/store/logo',
    headers: {'Content-Type': undefined },
    transformRequest: function (data) {
        var formData = new FormData();

        formData.append('store', new Blob([angular.toJson(data.store)], {
            type: "application/json"
        }));
        formData.append("file", data.file);
        return formData;
    },
    data: { store: $scope.selectedStore, file: $scope.myFile }

}).
success(function (data, status, headers, config) {
});

【讨论】:

  • @Stjin Geukens 它只是将 blob 插入到 db 中,而不是它自己的文件中:/ 文件的内容类型仍未定义..
猜你喜欢
  • 2014-12-22
  • 1970-01-01
  • 1970-01-01
  • 2018-02-03
  • 2019-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多