我正在尝试在同一多部分POST请求中将文件和一些json发送到我的REST端点。该请求是使用axios库直接从javascript发出的,如下面的方法所示。
doAjaxPost() {
var formData = new FormData();
var file = document.querySelector('#file');
formData.append("file", file.files[0]);
formData.append("document", documentJson);
axios({
method: 'post',
url: 'http://192.168.1.69:8080/api/files',
data: formData,
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
}
然而,问题是,当我检查在网络选项卡Chrome开发人员工具的要求,我觉得没有Content-Type
现场document
,而file
现场Content-Type
是application/pdf
(我将送一个PDF文件)。
在服务器Content-Type
上document
是text/plain;charset=us-ascii
。
更新:
我设法通过邮递员document
以.json
文件形式发送了正确的请求。尽管我发现这仅适用于Linux / Mac。
要设置内容类型,您需要传递类似文件的对象。您可以使用创建一个Blob
。
const obj = {
hello: "world"
};
const json = JSON.stringify(obj);
const blob = new Blob([json], {
type: 'application/json'
});
const data = new FormData();
data.append("document", blob);
axios({
method: 'post',
url: '/sample',
data: data,
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句