Search code examples
reactjsfilebase64blobcloudinary

Convert blob url to file or Base64 to upload to cloudinary


I have converted the file to blob url by creating a canvas, Now I want to convert blob url to either file type or base64 type to upload to cloudinary. But it seems very challenging to me, as none of them are working.

The below code is to convert the images to the blob url, acutally I am square cropping them

CanvasUtils.js

export async function getCroppedImg(
  imageSrc,
  pixelCrop,
  ...
) {
  ...
 return new Promise((resolve) => {
    canvas.toBlob((file) => {
      resolve(URL.createObjectURL(file));
    }, "image/png");
  });

My try's:

  1. Converting blob url to blob oject and then to file format

     for (let i = 0; i < imageUrls.length; i++) {
       console.log("This is from within the loop: imageURL", imageUrls[i]);
    let blob = new Blob([imageUrls[i]], { type: "image/jpg" });
    console.log("Blob is ", blob);
       var myFile = blobToFile(blob, "myimage.jpg");
    
    // uploading code goes here [find the code below]
    
    }
    
  2. Converting blob url to blob oject and then to base64

     let reader = new FileReader();
       reader.readAsDataURL(blob); // converts the blob to base64 and calls onload
    
       reader.onloadend = async function () {
         let myFile = reader.result; // data url
         // uploading code goes here [find the code below]
       }
    

The uploading code to save it in cloudinary goes like.

console.log(typeof myFile);
        data.append("file", myFile);
        data.append("upload_preset", "myPreset");

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

   

Output for try 1 goes like: enter image description here

Output for try 2 goes like: enter image description here

What is the good request then ??


Solution

  • In both the cases you are actually converting the imageUrl into blob. For some reason it doesn't work.

    Instead converting the imageUrl directly to the blob worked for me.

    The code goes like:

    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 use the function like this.

    const myImage = await getBase64FromUrl(imageUrls[i]);