Search code examples
reactjsuploadbase64blobcloudinary

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


I am trying to crop images from the selected files so, it is getting converted into blob,

Now i am facing difficulty in uploading them to the cloudinary , as it says its a bad request and not getting uploaded.

The code goes like,

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 is

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

Solution

  • Instead of actually converting the imageUrl into blob and then base64. Directly convert the imageUrl into Base64.

    Using the following 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);
          };
        });
      };
    

    And then in your code.

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