使用axios在POST multipart / form-data请求中发送文件和json [英] sending file and json in POST multipart/form-data request with axios
问题描述
我正在尝试将同一个多部分POST请求中的文件和一些json发送到我的REST端点。该请求直接来自使用axios库的javascript,如下面的方法所示。
I am trying to send a file and some json in the same multipart POST request to my REST endpoint. The request is made directly from javascript using axios library as shown in the method below.
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文件)。
However, the problem is when I inspect the request in chrome developer tools in the network tab, I find no Content-Type
field for document
, while for file
field Content-Type
is application/pdf
(I'm sending a pdf file).
在服务器上
是文档
的Content-Type text / plain; charset = us-ascii
。
On the server Content-Type
for document
is text/plain;charset=us-ascii
.
更新:
我设法通过Postman发送正确的请求,发送 document
作为 .json
文件。虽然我发现这只适用于Linux / Mac。
I managed to make a correct request via Postman, by sending document
as a .json
file. Though I discovered this only works on Linux/Mac.
推荐答案
要设置内容类型,您需要传递类似文件宾语。您可以使用 Blob
创建一个。
To set a content-type you need to pass a file-like object. You can create one using a 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,
})
这篇关于使用axios在POST multipart / form-data请求中发送文件和json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!