【发布时间】:2017-05-13 10:30:32
【问题描述】:
我正在尝试通过 API 将文件上传到远程 Spring 服务器,即使我已经将数据转换为表单数据,我仍然不断收到不支持的媒体类型错误 (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"
}
--更新--
好吧,我在阅读request的文档后才发现,如果你使用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
【问题讨论】:
标签: node.js spring http express multipartform-data