获取包含多部分表单数据的帖子

问题描述 投票:61回答:2

我正在获取这样的URL:

fetch(url, {
  mode: 'no-cors',
  method: method || null,
  headers: {
    'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
    'Content-Type': 'multipart/form-data'
  },
  body: JSON.stringify(data) || null,
}).then(function(response) {
  console.log(response.status)
  console.log("response");
  console.log(response)
})

我的API期望数据为multipart/form-data,所以我正在使用这种类型的content-type ...但是它给我一个状态码为400的响应。

我的代码怎么了?

javascript fetch fetch-api
2个回答
110
投票

您将Content-Type设置为multipart/form-data,但随后在主体数据上使用JSON.stringify,这将返回application/json。您的内容类型不匹配。

您将需要将数据编码为multipart/form-data,而不是json。上传文件时通常使用multipart/form-data,并且比application/x-www-form-urlencoded(HTML表单的默认设置)复杂一些。

multipart/form-data的规格可以在RFC 1867中找到。

有关如何通过javascript提交此类数据的指南,请参见here

基本思想是使用[FormData] [1]对象(IE <10中不支持:]

async function sendData(url, data) {
  var formData  = new FormData();

  for(var name in data) {
    formData.append(name, data[name]);
  }

  const response = await fetch(url, {
    method: 'POST',
    body: formData
  });

  // ...
}

Per https://muffinman.io/uploading-files-using-fetch-multipart-form-data/ make sure *not* to set the `Content-Type` header. The browser will set it for you, including the `boundary` parameter.


  [1]: https://developer.mozilla.org/en-US/docs/Web/API/FormData


14
投票

我最近正在与IPFS合作,并解决了这个问题。 IPFS上载文件的curl示例如下所示:

curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"

[基本思想是每个部分(在boundary中用字符串分割为--)都有自己的标头(例如,第二部分中的Content-Type。)FormData对象为您管理所有这些,因此这是实现我们目标的更好方法。

这将转换为获取API,如下所示:

FormData
© www.soinside.com 2019 - 2024. All rights reserved.