【问题标题】:Express parse file sent with Javascript Fetch API使用 Javascript Fetch API 发送的快速解析文件
【发布时间】:2021-07-13 22:04:34
【问题描述】:

我正在制作一个使用我编写的 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() 保存它,它返回此错误:

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

【问题讨论】:

    标签: javascript express file api-design


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

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

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

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

      【讨论】:

      • 考虑到这篇文章的 cmets 和答案,我决定使用该标题:stackoverflow.com/questions/36067767/…
      • @UlisesViña — 相信所有的答案,告诉你不要因为一个错误的评论说你应该这样做。
      • 你是对的。我会标记你的答案,因为你是正确的(虽然有点粗鲁)。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 2018-12-09
      • 1970-01-01
      • 2017-09-13
      相关资源
      最近更新 更多