使用 Fetch API 和 cross-fetch polyfill 在文件输入更改时上传文件

Using Fetch API with cross-fetch polyfill to upload file on file-input change

我正在使用 Fetch API 和 cross-fetch polyfill https://www.npmjs.com/package/cross-fetch

在 SO 上放屁几个小时,试图使用它上传文件。无论我做什么,我似乎都无法避免 'unsupported BodyInit type' 错误。

<input
    name="file"
    type="file"
    onChange={event => {
      event.preventDefault();
      var f = event.target.files[0];
      var data = new FormData();
      data.append("file", f);

      fetch("/my-api", {
        method: "POST",
        body: data
      });
    }}
  />

这是一个可运行的例子:https://codesandbox.io/s/v08lpj24wy

当然,我不会直接在 onChange 处理程序中执行此类操作,但该示例说明了错误。我做错了什么?

fetchreturns一个承诺。在您调用 then

之前它不会执行任何操作

编辑

如果您使用 Request 对象调用 fetch,错误就会消失

var req = new Request("/my-api", {
          method: "POST",
          body: data
        });

fetch(req)
    .then(() => console.log("ok"))
    .catch(() => console.error("not ok"));

事实证明,您的 import fetch from "cross-fetch" 通过破坏 blob 和 FormData 的解析来错误地填充获取。只需删除导入并查看一切正常。

实际上,cross-fetch 用于在浏览器环境中获取的 github 获取存在问题。 http://github.com/github/fetch/issues/601

You can't pass a file directly as body. You must take the 2nd approach by wrapping it in a FormData. When passing a FormData to body, you must not set any Content-Type header for the request. Instead, the browser will choose the appropriate multipart/form-data value.