使用 axios 在 POST multipart/form-data 请求中发送文件和 json [英] sending file and json in POST multipart/form-data request with axios

查看:216
本文介绍了使用 axios 在 POST multipart/form-data 请求中发送文件和 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在同一个多部分 POST 请求中向我的 REST 端点发送一个文件和一些 json.该请求是使用 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 开发者工具中检查请求时,我发现 document 没有 Content-Type 字段,而 >file 字段 Content-Typeapplication/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).

在服务器上,documentContent-Typetext/plain;charset=us-ascii.

On the server Content-Type for document is text/plain;charset=us-ascii.

更新:

通过将 document 作为 .json 文件发送,我设法通过 Postman 提出了正确的请求.虽然我发现这仅适用于 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆