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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50774176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:40:35  来源:igfitidea点击:

sending file and json in POST multipart/form-data request with axios

javascriptjsonfileaxiosmultipartform-data

提问by pavlee

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.

我试图在同一个多部分 POST 请求中向我的 REST 端点发送一个文件和一些 json。该请求是使用 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);
    });
}

However, the problem is when I inspect the request in chrome developer tools in the network tab, I find no Content-Typefield for document, while for filefield Content-Typeis application/pdf(I'm sending a pdf file).

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

Request shown in network inspector

请求显示在网络检查器中

On the server Content-Typefor documentis text/plain;charset=us-ascii.

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

Update:

更新:

I managed to make a correct request via Postman, by sending documentas a .jsonfile. Though I discovered this only works on Linux/Mac.

我设法通过 Postmandocument.json文件形式发送正确的请求。虽然我发现这仅适用于 Linux/Mac。

回答by Quentin

To set a content-type you need to pass a file-like object. You can create one using a Blob.

要设置内容类型,您需要传递一个类似文件的对象。您可以使用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,
})

回答by eth3rnit3

you only need to add the right headers to your request

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

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