1
votes

I am trying to display an image when uploaded and then add that image to firebase. I was able to display the image but when I try to upload i get an error message that I have not been able to figure out. Here is my code

html

<input type="file" accept="image/*"  onchange="showMainImage(this)" />
  <br/>
<img id="thumbnil" style="width:40%; margin-top:10px;"  src="" alt="image"/>

JS

 function showMainImage(fileInput) {
    var files = fileInput.files;
    for (var i = 0; i < files.length; i++) {           
        var file = files[i];
        var imageType = /image.*/;     
        if (!file.type.match(imageType)) {
            continue;
        }           
        var img=document.getElementById("thumbnil");            
        img.file = file;    
        var reader = new FileReader();
        reader.onload = (function(aImg) { 
            return function(e) { 
                aImg.src = e.target.result; 
            }; 
        })(img);
        reader.readAsDataURL(file);
    }

  firebase.auth().onAuthStateChanged((user) => {
    if (user) {

        database = firebase.database();

        var BusinessesId = firebase.auth().currentUser.uid;

 //Get file

        var filename = files.name;

        //Create storage reference
        var storageRef = firebase.storage().ref("ProductImages/"+BusinessesId+"/"+filename);

        //Upload file
        var task = storageRef.put(files).then(function(snapshot) {
                console.log('Uploaded', snapshot.totalBytes, 'bytes.');
                var url = snapshot.downloadURL;
                // productImageUrl.value = url;
                console.log('File available at', url);
                // [START_EXCLUDE]
              }).catch(function(error) {
                // [START onfailure]
                console.error('Upload failed:', error);
                // [END onfailure]
              });
              // [END oncomplete]


              }

     })

}

I get this from the console

{t: "storage/invalid-argument", e: "Firebase Storage: Invalid argument in put at index 0: Expected Blob or File.", n: null, r: "FirebaseError"} code : (...) e : "Firebase Storage: Invalid argument in put at index 0: Expected Blob or File."

from the error message I think the file is not being properly formated. How can I fix this error and upload the file?

1

1 Answers

0
votes

The method put takes as first parameter non-null Blob, non-null Uint8Array, or non-null ArrayBuffer. https://firebase.google.com/docs/reference/js/firebase.storage.Reference#put

Consider switching to putString method, so you can put any String in any format you want. https://firebase.google.com/docs/reference/js/firebase.storage.Reference#putString

You should transform your object first.

This is my implementation: I've used also the STATE_CHANGED to monitor the uploading percentage of the picture:

self.uploadPicture = function() {
   var userId = self.user().uid;
   var storageRef = firebase.storage().ref().child('images/'+userId);
   var data = self.fileData().dataURL();
   var uploadTask = storageRef.putString(data, 'data_url');
   uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
      function(snapshot) {
        // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
        var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        self.percentage(Math.round(progress));
      }, function(error) {
            toastr.error(error.code,error.message);
    }, function() {
      toastr.success("Immagine profilo Aggiornata");
      self.savedPicture(true);
    });