簡體   English   中英

使用 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]);
      });
    }
  };

Output 是

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。

使用以下 function。

    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]);

   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM