我试图将相同的多部分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字段,而对于文件字段,Content-Type是application / pdf(我正在发送pdf文件).
在服务器上,文档的Content-Type是text / plain; charset = us-ascii.
更新:
我设法通过Postman发送一个正确的请求,将文件作为.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,
})
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!