无法在“FormData”上执行“追加”:参数 2 不是“Blob”类型

新手上路,请多包涵

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

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

所以如果后面只需要更新“1”,发送的对象只会包含 {"1": Blob}

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

无法在“FormData”上执行“追加”:参数 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"
  }
}

如何解决这个问题?谢谢!

原文由 DoneDeal0 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 805
2 个回答

您不应该在控制台中看到 FormData 对象的内容,因为它不可序列化。您可以改为检查请求负载,检查浏览器开发工具中的“网络”选项卡,找到您的请求并查看“标头”选项卡底部以查看“FormData”日志。你会看到这样的东西: 在此处输入图像描述

此外,您应该在 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>

原文由 pearcake 发布,翻译遵循 CC BY-SA 4.0 许可协议

我在我的 React Native 应用程序上遇到了这个问题。为了解决它,我必须将图像路径转换为 blob。下面给出了我的句柄上传功能的代码。

 const handleUpload = async () => {
    if (selectedImage.localUri !== '') {

        const image_uri =  Platform.OS === 'ios' ? selectedImage.localUri.replace('file://', '') : selectedImage.localUri;

        const response = await fetch(image_uri);
        const blob = await response.blob();

        const formData = new FormData();
        formData.append('image', blob, "xray_image.jpg");

        setLoading(true);

        axios.post("https://...", formData)
            .then((result) => {
               console.log(result);
            })
            .catch((err) => {
                console.log(err);

            });

    } else {
        console.log("Select a file error message");
    }
};

原文由 Roshinie Jayasundara 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题