【发布时间】: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);
}
因此,尽管这可行,但我确信有两件事可以简化:
- Angular:还不错,但代码似乎比它应该的复杂得多
- 春天:这是最烦人的;文件没问题,但我需要将
store的参数类型设置为String,否则Spring 会给我一个'找不到匹配的编辑器或转换策略'。不知何故,请求参数不被识别为 JSON,我猜这是因为将内容类型设置为未定义但如果我没有得到:'org.springframework.web.multipart.MultipartException:当前请求是不是多部分请求'?
顺便说一下,分别发布两者都很好。 JSON 被转换为正确的类型并接收到文件。到目前为止,我已经花了几个小时让混合模式(以一种干净的方式)工作,但没有运气......
【问题讨论】:
-
你看过这个答案了吗:stackoverflow.com/a/25183266/2264997
-
不,看起来信息量很大,会尽快查看。发送。
标签: json angularjs spring rest multipartform-data