amorim
amorim

Reputation: 79

How to upload image file to firebase storage

I'm trying to upload an image to the firebase storage so i can progress on my project, but when i run the following code, the image stored looks like this: enter image description here

I read the documentation and it says it have to be a File or Blob, so i came here to ask, any help is appreciated

This is the upload code:

const RegisterProperty = () => {

    const cameraImage = require('../pics/camera.png')
    const baseImage = require('../pics/baseImage.jpg')
    const imagemTeste = 'https://i.postimg.cc/mrfdKk2M/smoking.png'

    const uploadImagem = async () => {
        // const imageBlob = new Blob([baseImage],"filename.jpg",{type: 'image/jpeg'})
        // const response = await fetch(imagemTeste)
        // const imageBlob = await response.blob()

        uploadBytes(storageRef, baseImage, metadata).then(() => {
            console.log('Uploaded')
        })
        console.log(typeof(imagemTeste2))
    }
}

Error:

enter image description here

Upvotes: 1

Views: 832

Answers (2)

work for me try this one in picimage fuction

 const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
  mediaTypes: ImagePicker.MediaTypeOptions.Images,
  allowsEditing: true,
  aspect: [1, 1],
  quality: 1,
});

if (!result.canceled) {
  console.log("this is image link",result.assets[0].uri)
  setImage(result.assets[0].uri);
  const url = result.assets[0].uri
  
  
  function urlToBlob(url) {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.addEventListener('error', reject);
      xhr.addEventListener('readystatechange', () => {
        if (xhr.readyState === 4) {
          resolve(xhr.response);
        }
      });
      xhr.open('GET', url);
      xhr.responseType = 'blob'; // convert type
      xhr.send();
    });
  }
  const blob = await urlToBlob(url);
   setBlobImage(blob)
}

}

Upvotes: 0

Slbox
Slbox

Reputation: 13138

Take the local path use it like below.

Note that there is a newer syntax for blobs, but we're not using it yet so I can only share this:

function urlToBlob(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.addEventListener('error', reject);
    xhr.addEventListener('readystatechange', () => {
      if (xhr.readyState === 4) {
        resolve(xhr.response);
      }
    });
    xhr.open('GET', url);
    xhr.responseType = 'blob'; // convert type
    xhr.send();
  });
}


const blob = await urlToBlob(localPath);

uploadBytes(storageRef, blob, metadata).then(() => {
  console.log('Uploaded')
})

Upvotes: 1

Related Questions