0

My following code for uploading an image to firebase storage is working properly.

But I want to reduce the file size of "file1 (The image)" to 100px*100px. And upload it to firebase storage.

    function uploadImage() {

     const ref = firebase.storage().ref();
     const file1 = document.querySelector("#photo").files[0];
                
      
      const metadata = {
        contentType: file1.type
      };
      const task = ref.child(mydata.uid).put(file1, metadata);
      task
        .then(snapshot => snapshot.ref.getDownloadURL())
        .then(url => {
            db.collection('user').doc(mydata.docid).update({
              profilepic : url,
            });  
          const image = document.querySelector("#image")
          image.src = url;
          alert("uploaded")
        })
        .catch(console.error);
    }

Please provide the full code for uploading a resized image to the firebase storage.

1 Answers1

1

As your question appears to be for React, there is an npm package that does exactly this: React Image Resizer

After you wrap the resizer as outlined in the npm package documentation, you'll modify your code to be as follows:

async function uploadImage() {

    const ref = firebase.storage().ref();
    const file1 = document.querySelector("#photo").files[0];
    const resizedImg =  await resizeFile(file1);



    const metadata = {
        contentType: file1.type
    };
    const task = ref.child(mydata.uid).putString(resizedImg, 'base64', metadata);
    task
        .then(snapshot => snapshot.ref.getDownloadURL())
        .then(url => {
            db.collection('user').doc(mydata.docid).update({
                profilepic : url,
            });
            const image = document.querySelector("#image")
            image.src = url;
            alert("uploaded")
        })
        .catch(console.error);
}
Hydra
  • 950
  • 4
  • 7
  • But it's giving an error - Line 190:37: 'resizeFile' is not defined no-undef – Spandan Manna Aug 26 '21 at 18:01
  • @SpandanManna You need to use npm to install the package, and then wrap the resizer in your own function as outlined in Example 1 of the package documentation here: https://www.npmjs.com/package/react-image-file-resizer – Hydra Aug 26 '21 at 18:05