FlitchZy
FlitchZy

Reputation: 1

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.

Upvotes: -1

Views: 233

Answers (2)

minnow
minnow

Reputation: 361

It seems you are providing a url to the image blob/file instead of passing the file itself. Try changing line 8 to just var file = picker.files[0].

If that doesn’t work, try logging fileafter it is initialized to make sure it exists.

Upvotes: 0

Dharmaraj
Dharmaraj

Reputation: 50930

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

Upvotes: 1

Related Questions