如何在Spring restful服务中处理由文件和JSON对象组成的多部分请求? [英] How to process a multipart request consisting of a file and a JSON object in Spring restful service?
本文介绍了如何在Spring restful服务中处理由文件和JSON对象组成的多部分请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下资源(使用Spring 4.05.RELEASE实现),它接受一个文件和一个JSON对象:
I have the following resource (implemented using Spring 4.05.RELEASE) which accepts a file and a JSON object:
(PS activityTemplate是一个可序列化的实体类)
(P.S. activityTemplate is a serializable entity class)
...
@RequestMapping(value="/create", method=RequestMethod.POST)
public @ResponseBody ActivityTemplate createActivityTemplate(
@RequestPart ActivityTemplate activityTemplate, @RequestPart MultipartFile jarFile)
{
//process the file and JSON
}
...
这是我正在测试的表格:
and this is the form I am testing from:
<form method="POST" enctype="multipart/form-data"
action="http://localhost:8080/activityTemplates/create">
JSON: <input type="text" name="activityTemplate" value='/* the JSON object*/'><br />
File to upload: <input type="file" name="file">
<input type="submit" value="Upload">
</form>
这是我得到的错误:
There was an unexpected error (type=Unsupported Media Type, status=415).
Content type 'application/octet-stream' not supported
那么我该如何制作资源接受JSON对象作为multipart请求的一部分,或者我应该以不同的方式发送表单?
So how should I make the resource accept the JSON object as part of the multipart request, or should I be sending the form in a different way?
推荐答案
这我花了两天时间为我工作!
This took me two days to work for me!
客户(角度):
$scope.saveForm = function () {
var formData = new FormData();
var file = $scope.myFile;
var json = $scope.myJson;
formData.append("file", file);
formData.append("ad",JSON.stringify(json));//important: convert to string JSON!
var req = {
url: '/upload',
method: 'POST',
headers: {'Content-Type': undefined},
data: formData,
transformRequest: function (data, headersGetterFunction) {
return data;
}
};
春天(开机):
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody
Advertisement storeAd(@RequestPart("ad") String adString, @RequestPart("file") MultipartFile file) throws IOException {
Advertisement jsonAd = new ObjectMapper().readValue(adString, Advertisement.class);
//do whatever you want with your file and jsonAd
这篇关于如何在Spring restful服务中处理由文件和JSON对象组成的多部分请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文