Sahar Milis Sahar Milis - 1 month ago 42
Javascript Question

Firebase Web Storage - upload a file without specifying its name

I'm using Firebase Storage and everything works great.

How can I upload a file without specifying its name?

So the file will get a unique name by Firebase, like they do in the storage.

This is an example of what i'm using now:

firebase.initializeApp(config);
var fileUpload = document.getElementById("uploadFile").files;
var storageRef = firebase.storage().ref(fileUpload[0].name);
var uploadTask = storageRef.put(fileUpload[0]);


And I want to do someting like this:

firebase.initializeApp(config);
var fileUpload = document.getElementById("uploadFile").files;
var storageRef = firebase.storage().ref();
var uploadTask = storageRef.put(fileUpload[0]);


Appreciate any help you can provide. Thanks.

Answer

There is no built-in API to generate file names for you in Firebase Storage.

But similar to what the Firebase Database does, you can easily generate a filename client-side that is statistically guaranteed to be unique.

One way to do this would be to generate a UUID, such as with the guid() function from this answer:

var storageRef = firebase.storage().ref(guid());

Note that you'd lose the filename extension here, which is how Firebase Storage determines the file type. So more likely you'll want to determine the filename based on the local filename but then with something before it to make it unique.

var storageRef = firebase.storage().ref(guid()+fileUpload[0].name);

Given this combination, there's a pretty good chance that just prefixing with the local timestamp is unique already:

var storageRef = firebase.storage().ref(Date.now()+fileUpload[0].name);
Comments