0

I have the following code:

var file = document.getElementById("image1");
var filename = file.files[0].name;
//console.log("Archivo: " + filename);
var storageRef = firebase.storage().ref();
var ref = storageRef.child('imagenes/'+filename);

var reader = new FileReader();
var rawData;

reader.onload = function(e) {
    rawData = reader.result;   
}

reader.readAsBinaryString(file);

ref.put(rawData).then(function(snapshot){

});

File -> get the data file input (an image).

And I want convert this file to blob in the moment that the form is send, to upload to firebase storage the image in the format BLOB, how I can do this? I was used the fileReader, but always return the same error:

'readAsBinaryString' on 'FileReader': parameter 1 is not of type 'Blob'.

How do convert the file image to a blob?

Blue
  • 22,608
  • 7
  • 62
  • 92
Juanma Perez
  • 97
  • 4
  • 14

1 Answers1

0

You can't simply set rawData inside the onload function like you're doing. By the time ref.put() is run, the onload function will not have been called, so rawData will ALWAYS be undefined. ref.put() takes in the file as its parameter, so simply use ref.put(file.files[0]) (No reader required):

var file = document.getElementById("image1");
var filename = file.files[0].name;
//console.log("Archivo: " + filename);
var storageRef = firebase.storage().ref();
var ref = storageRef.child('imagenes/'+filename);

ref.put(file.files[0]).then(...);

See also the very common: How do I return the response from an asynchronous call?

Blue
  • 22,608
  • 7
  • 62
  • 92
  • Okay, but now, I have the next error: 'readAsBinaryString' on 'FileReader': parameter 1 is not of type 'Blob'. On the last line. – Juanma Perez Oct 15 '18 at 10:33
  • @JuanmaPerez See my edit. `file` is an HTML Input field. You want to access `.files[0]` to grab the actual file. – Blue Oct 15 '18 at 10:35
  • Before do the changes, Firebase response with this error: Argument in `put` at index 0: Expected Blob or File. reader.result not is the blob? – Juanma Perez Oct 15 '18 at 10:43
  • What happens if you just use `ref.put(file.files[0])` instead of doing anything with the reader? – Blue Oct 15 '18 at 10:45
  • Okay, just solved the problem, and working correctly. Thank you very much!! – Juanma Perez Oct 15 '18 at 10:54
  • @JuanmaPerez [This popped up a few days ago, just a heads up](https://medium.com/@scosta/why-firebase-sucks-ce5d2302eb20) – Blue Oct 15 '18 at 10:56