使用axios在POST multipart/form-data请求中发送文件和json

pav*_*lee 7 javascript json multipartform-data file axios

我试图将相同的多部分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);
    });
}
Run Code Online (Sandbox Code Playgroud)

但是,问题是当我在网络选项卡中的chrome开发人员工具中检查请求时,我找不到任何Content-Type字段document,而对于file字段Content-Typeapplication/pdf(我正在发送pdf文件).

请求显示在网络检查器中

在服务器Content-Typedocumenttext/plain;charset=us-ascii.

更新:

我设法让邮差通过一个正确的请求,通过发送document.json文件.虽然我发现这只适用于Linux/Mac.

Que*_*tin 27

要设置内容类型,您需要传递类文件对象.您可以使用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,
})
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,反正我已经运行了。唯一缺少的一行是我添加的`formData.append("file", file)`,它对我有用:) (6认同)
  • 你在哪里附加文件在这里?此代码示例中是否缺少它? (2认同)

小智 18

尝试这个。

doAjaxPost() {
    var formData = new FormData();
    var file = document.querySelector('#file');

    formData.append("file", file.files[0]);
    // formData.append("document", documentJson); instead of this, use the line below.
    formData.append("document", JSON.stringify(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);
    });
}
Run Code Online (Sandbox Code Playgroud)

您可以在后端解码这个字符串化的 JSON。