Search code examples
javascriptfirebasefirebase-storage

How to upload a img to firebase storage correctly (javascript)?


Im having problem uploading image to firebase storage, it keeps uploading 9B file to storage even if selected file is a 100mb file. It is showing the progress as NaN%, once i successfully uploaded a image to firebase storage but now im failing 😭 here is the code,

const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const storage = getStorage();

var picker = document.getElementById('img');

picker.onchange = function(){
var file = window.URL.createObjectURL(picker.files[0]);
var filename = picker.files[0].name;
const storageRef = ref(storage, 'icons/' + filename);

// 'file' comes from the Blob or File API
uploadBytes(storageRef, file).then((snapshot) => {
  console.log('Uploaded a blob or file!');
 });
}

I tried many options i doesn't know why it is not working, i want to upload image & get download url.


Solution

  • You have to pass the actual File object to uploadBytes and not the object URL. Try:

    picker.onchange = function() {
        const file = picker.files[0];
        if (!file) {
          alert("No file selected")
          return
        }
      
        const storageRef = ref(storage, 'icons/' + file.name);
    
        uploadBytes(storageRef, file).then((snapshot) => {
            console.log('Uploaded a blob or file!');
        }).catch(e => console.log(e));
    }