使用 Javascript Fetch API 发送的快速解析文件

Express parse file sent with Javascript Fetch API

我正在制作一个使用我写的 API 的应用程序,问题是,我需要客户端将图像发送到 API 然后将其保存在服务器端,我使用文件输入和以下脚本成功发送图像:

      const upload = _ => {
        let form = new FormData();
        form.append("file", document.getElementById("my-file-selector").files[0])
        fetch('http://localhost:3377/me/uploadPfp', {
          method: 'POST',
          headers: {
              "Authorization": "<%= locals.user.token %>",
              "Content-Type": "application/x-www-form-urlencoded"
          },
          body: form,
          }).then(
            response => response.json()
          ).then(
            success => console.log(success)
          ).catch(
            error => console.log(error)
          );
      };

服务器端它似乎可以工作,但我无法使用 fs.writeFile() 保存它,它 returns 这个错误:

TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView.

但是当我console.log接收到文件时,会发生这种情况: Receipt Image

"Content-Type": "application/x-www-form-urlencoded"

您没有发送 URL 编码数据,所以不要声称您是。

fetch 可以从您传递给它的 FormData 对象中推断出正确的内容类型。

您的服务器端代码相信您的内容类型并误解了数据。

这好像是你在使用图片文件,而是在if语句中使用这段代码

**fs.writeFile('file.txt', img.toString(), err){
  if (err) throw err;
  console.log('The file has been saved!');
}**

这段代码将您的图像转换并存储为字符串。