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

sending file and json in POST multipart/form-data request with 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);
    });
}

但是,问题是当我在网络选项卡的 chrome 开发人员工具中检查请求时,我发现 document 没有 Content-Type 字段,而 file 字段 Content-Typeapplication/pdf(我正在发送一个 pdf 文件)。

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

更新:

我设法通过 Postman 发出了正确的请求,将 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,
})

您只需要在您的请求中添加正确的headers

axios({
  method: 'post',
  url: 'http://192.168.1.69:8080/api/files',
  data: formData,
  header: {
            'Accept': 'application/json',
            'Content-Type': 'multipart/form-data',
          },
    })

试试这个。

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);
    });
}

您可以在 back-end 中解码这个字符串化的 JSON。