使用 React 将 blob 文件上传到 cloudinary,Cloudinary Bad Request 400

Upload blob file to cloudinary using React, Cloudinary Bad Request 400

我正在尝试从所选文件中裁剪图像,因此它正在转换为 blob,

现在我在将它们上传到 cloudinary 时遇到困难,因为它说这是一个错误的请求并且 没有上传。

代码如下,

const blobToBase64 = (blob) => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    return new Promise((resolve) => {
      reader.onloadend = () => {
        resolve(reader.result);
      };
    });
  };
const uploadFilesToCloud = async () => {
    const data = new FormData();
    for (let i = 0; i < imageUrls.length; i++) {
      console.log("This is from within the loop: imageURL", imageUrls[i]);

      blobToBase64(new Blob([imageUrls[i]])).then(async (myFile) => {
        console.log(typeof myFile); // res is base64 now
        console.log("This is from within the loop file BaseToBase64", myFile);

        data.append("file", myFile);
        data.append("upload_preset", "theVegCakeShop");

        const res = await fetch(
          "https://api.cloudinary.com/v1_1/dpurb6xes/image/upload",
          {
            method: "Post",
            body: data,
          }
        );
        const response = await res.json();
        console.log(response.secure_url);

        setImages((prev) => [...prev, response.secure_url]);
      });
    }
  };

输出是

This is from within the loop: imageURL blob:http://localhost:8888/7fbda7a7-e4d5-4716-a888-c9dbd80cd4fb
string
This is from within the loop file BaseToBase64 data:application/octet-stream;base64,YmxvYjpodHRwOi8vbG9jYWxob3N0Ojg4ODgvN2ZiZGE3YTctZTRkNS00NzE2LWE4ODgtYzlkYmQ4MGNkNGZi
POST https://api.cloudinary.com/v1_1/dpurb6xes/image/upload 400 (Bad Request)
undefined

您的 base64 数据看起来不对,它的 mimetype 是 application/octet-stream,例如它应该类似于 image/png。所以看起来你传递的图像 URL 并不是真正的图像 - 一旦你开始解码实际图像,它应该可以正常上传。

而不是实际将 imageUrl 转换为 blob,然后再转换为 base64。直接将imageUrl转成Base64.

使用以下函数。

    const getBase64FromUrl = async (url) => {
    const data = await fetch(url);
    const blob = await data.blob();
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onloadend = () => {
        const base64data = reader.result;
        resolve(base64data);
      };
    });
  };

然后在你的代码中。

for (let i = 0; i < imageUrls.length; i++) {
      const finalImage = await getBase64FromUrl(imageUrls[i]);
        data.append("file", myFile);
    data.append("upload_preset", "theVegCakeShop");

    const res = await fetch(
      "https://api.cloudinary.com/v1_1/dpurb6xes/image/upload",
      {
        method: "Post",
        body: data,
      }
    );
    const response = await res.json();
    console.log(response.secure_url);

    setImages((prev) => [...prev, response.secure_url]);

   }