代码之家  ›  专栏  ›  技术社区  ›  pavlee

使用axios在post multipart/form数据请求中发送文件和json

  •  6
  • pavlee  · 技术社区  · 7 年前

    我正试图在同一个多部分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);
        });
    }
    

    但是,问题是当我在网络选项卡中检查chrome开发工具中的请求时,发现没有 Content-Type 字段为 document 而对于 file 领域 内容类型 application/pdf (我正在发送一个pdf文件)。

    Request shown in network inspector

    在服务器上 内容类型 对于 文件 text/plain;charset=us-ascii .

    更新:

    我设法通过邮递员发出一个正确的请求 文件 作为一个 .json 文件。尽管我发现这只适用于linux/mac。

    2 回复  |  直到 7 年前
        1
  •  23
  •   Quentin    7 年前

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

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

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