gpt4 book ai didi

java - Spring Restful服务中如何处理由文件和JSON对象组成的多部分请求?

转载 作者:IT老高 更新时间:2023-10-28 13:50:48 25 4
gpt4 key购买 nike

我有以下资源(使用 Spring 4.05.RELEASE 实现),它接受一个文件和一个 JSON 对象:

(P.S.activityTemplate 是一个可序列化的实体类)

...
@RequestMapping(value="/create", method=RequestMethod.POST)
public @ResponseBody ActivityTemplate createActivityTemplate(
@RequestPart ActivityTemplate activityTemplate, @RequestPart MultipartFile jarFile)
{
//process the file and JSON
}
...

这是我正在测试的表格:

<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 对象作为多部分请求的一部分,或者我应该以不同的方式发送表单?

最佳答案

这花了我两天的时间才为我工作!

客户端(角度):

$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;
}
};

Spring (启动):

@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

关于java - Spring Restful服务中如何处理由文件和JSON对象组成的多部分请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27294838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com