无法在'FormData'上执行'append':参数2的类型不是'Blob'

时间:2020-09-24 17:28:16

标签: javascript file-upload form-data

我有一个上传器,允许用户上传多张图片。为了只创建或更新他要添加/更改的图像,我更新了一个如下所示的对象:

{main: Blob, "1": Blob, "2":Blob}

因此,如果以后只需要更新“ 1”,则发送的对象将只包含 {"1": Blob}

单击保存时,它会触发一个函数,该函数应该将图像附加到formData()。遗憾的是,formData从未更新。我遇到以下错误:

无法在'FormData'上执行'append':参数2不是'Blob'类型。

export async function uploadImages(files, userId) {
  try {
    const images = new FormData();
    files.main && images.append("image", files.main, "main");
    files[1] && images.append("image", files[1], "1");
    files[2] && images.append("image", files[2], "2");

    const res = await ax.post(process.env.SERVER_URL + "/upload-images", {
      images,
      userId,
    });
    return "success"
  } catch (err) {
    return "error"
  }
}

如何解决此问题?谢谢!

3 个答案:

答案 0 :(得分:2)

您不应在控制台中看到FormData对象的内容,因为它不可序列化。您可以改为检查请求有效负载,在浏览器开发工具中检查“网络”选项卡,找到您的请求,然后在“标题”选项卡的底部查看“ FormData”日志。您将看到如下内容: enter image description here

此外,您应该在axios中将标头“ Content-Type”设置为“ multipart / form-data”。 这是工作示例:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  </head>
  <body>
    <input type="file" multiple id="filepicker" />

    <button id="send">Send</button>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.20.0/axios.min.js"></script>
    <script>
      const myformData = new FormData();

      document
        .querySelector('#filepicker')
        .addEventListener('change', function (event) {
          const { files } = event.target;

          Object.values(files).forEach(function (file, index) {
            myformData.append(index, file);
          });
        });

      document.querySelector('#send').addEventListener('click', function () {
        axios({
          method: 'post',
          url: 'http://google.com',
          data: myformData,
          headers: { 'Content-Type': 'multipart/form-data' },
        })
          .then((response) => console.log(response))
          .catch((err) => console.log(err));
      });
    </script>
  </body>
</html>

答案 1 :(得分:0)

export async function uploadImages(files, userId) {
  try {
    const images = new FormData();
    for(const file of files){
        images.append("image", file);
    }
    const res = await ax.post(process.env.SERVER_URL + "/upload-images", {
      images,
      userId,
    });
    return "success"
  } catch (err) {
    return "error"
  }
}

答案 2 :(得分:0)

您必须将扩展名与名称一起传递

files[1] && images.append("image", files[1], "custom-name.jpg");