skip to Main Content

In my React project I have a google oAuth API which I’m retrieving the google image url from the response:

const userInfoResponse = await axios.get('https://www.googleapis.com/oauth2/v3/userinfo', {
   headers: { Authorization: `Bearer ${googleResponse.access_token}` }
});

const google_image = userInfoResponse.data.picture;
console.log(google_image);
//https://lh3.googleusercontent.com/a/ACg8ocKjThtaGf5USLuL2LBMBuYxfDG0gDdM-RLA_I__UvNI3p_2Hlk=s96-c

Now I want to convert this URL to a File Object. So i tried to first convert this to a blob and then use the blob to construct a File but is not working as expected!

const googleImageResponse = await fetch(google_image);
const blob = await googleImageResponse.blob();
const googleImageFile = new File([blob], "profileAvatar.png");
const formData = new FormData();
formData.append('profile', googleImageFile);
formData.append('record', userResponse.data.id);

But in the above code the blob type is text/html and not an image. So when I’m adding the File to the FormData is failing to render it because the image is not of image type.


Required Solution:

I want to be able to:

  • Get Image URL from Google Response (e.g. https://lh3.googleusercontent.com/a/ACg8ocKjThtaGf5USLuL2LBMBuYxfDG0gDdM-RLA_I__UvNI3p_2Hlk=s96-c)
  • Convert Image URL to File
  • Pass File to FormData
  • Pass FormData toan API!

2

Answers


  1. Chosen as BEST ANSWER

    INTERACTIVE SOLUTION BASED ON @Emiel's Reply

    const getFormData = async(url) => {
      const googleImageResponse = await fetch(url);
      const blob = await googleImageResponse.blob();
    
      //FIX HERE
      const googleImageFile = new File([blob], 'profileAvatar.png', {
        type: blob.type || 'image/png'
      });
      //END OF FIX
    
      const imageURL = URL.createObjectURL(googleImageFile);
      document.getElementById("myImg").src = imageURL;
      document.getElementById("imgName").textContent = googleImageFile.name;
    };
    
    
    //BUTTON EVENT
    document.getElementById("loadImageButton").addEventListener("click", async() => {
      const url = document.getElementById("imageUrlInput").value;
      await getFormData(url);
    });
    #myImg {
      width: 25px;
      height: 25px;
    }
    <input type="text" id="imageUrlInput" value="https://lh3.googleusercontent.com/a/ACg8ocKjThtaGf5USLuL2LBMBuYxfDG0gDdM-RLA_I__UvNI3p_2Hlk=s96-c" placeholder="Enter image URL" />
    <button id="loadImageButton">Load Image</button>
    
    <p id="imgName"></p>
    <img id="myImg" />


  2. Add the MIME type explicitly by using the options parameter in the File constructor.

    const googleImageFile = new File([blob], 'profileAvatar.png', {
      type: blob.type || 'image/png'
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search