将表单数据上传到弹簧服务器时不受支持的媒体类型
我试图通过API将文件上传到远程弹簧服务器,并且即使我已经将数据转换为表单数据,我仍然收到不受支持的媒体类型错误(415)。
这里是快递http post请求:
var FormData = require('form-data');
var fs = require('fs');
var form = new FormData();
form.append('pid', params.pid);
form.append('deliveryAttachment', fs.createReadStream(params.deliveryAttachment.path));
var url = someDomain + '/proj/new/deliveryAttachment';
requestLib({
url: url,
method: "POST",
jar: getJar(),
form: form
},function (error, response, body){
console.log(body)
});
这里是Java Spring控制器的参考:
@RequestMapping(value = "proj/new/deliveryAttachment", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE)
public String insertDeliveryAttachment(@RequestParam("pid") long pid,
@RequestParam("deliveryAttachment") MultipartFile file) {
try {
DeliveryAttachment a = new DeliveryAttachment(file.getOriginalFilename(), pid);
ps.insertDeliveryAttachment(a, file.getBytes());
return String.valueOf(a.id);
} catch (IOException e) {
return "-1";
}
}
这是表单数据控制台日志:
415回应:
{
"timestamp": 1494671395688,
"status": 415,
"error": "Unsupported Media Type",
"exception": "org.springframework.web.HttpMediaTypeNotSupportedException",
"message": "Content type 'application/x-www-form-urlencoded' not supported",
"path": "/proj/new/deliveryAttachment"
}
--UPDATE--
好的,我在阅读请求的文档后发现,如果您使用form
作为数据的持有者,它会将数据视为application/x-www-form-urlencoded
例如; request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ ... });
同时multipart/form-data
的正确关键是formData
例如; request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) { ... });
我试过了,现在它给了我一个新的错误:
TypeError: Cannot read property 'name' of null at FormData._getContentDisposition
看起来你正在发送一个带有Content-Type: 'application/x-www-form-urlencoded'
的POST请求Content-Type: 'application/x-www-form-urlencoded'
,你的SpringController的insertDeliveryAttachment()
multipart/form-data
MIME类型。
我建议您将insertDeliveryAttachment()
方法上的消耗MIME类型更改为MediaType.APPLICATION_FORM_URLENCODED_VALUE
我解决了它。 我没有使用FormData,只是在一个对象中插入值并且工作。
var data = {
pid: params.pid,
deliveryAttachment: fs.createReadStream(params.deliveryAttachment[0].path)
};
var url = wfDomain + '/proj/new/deliveryAttachment';
requestLib({
url: url,
method: "POST",
headers: {
'Content-Type': 'multipart/form-data'
},
jar: getJar(),
formData: data
},function (error, response, body){ ... });
链接地址: http://www.djcxy.com/p/48729.html
上一篇: Unsupported media type when uploading form data to spring server
下一篇: File upload in Spring Boot: Uploading, validation, and exception handling