Am creating a hybrid app using Ionic, (ng)Cordova and Firebase storage.
Previously, pairing Cordova media capture (e.g. for capturing a video) and cordova file transfer (for uploading it somewhere) worked something like this question states.
I'm struggling to work out how to achieve the same thing with the new Firebase Storage upload process, which doesn't use a server address:
var uploadTask = storageRef.child('videos/' + file.name).put(file);
I get the feeling that I now need to add another step for actually accessing the file from the device - this was previously handled by the file transfer plugin.
I may be missing something very obvious - if so, apologes and thanks.
Right, I finally got this working.
If you want to use the new firebase storage upload method described here you no longer want to use the Cordova FileTransfer plugin (which did some of the dirty work for you).
You now need to read the file first, using the (ng)Cordova File plugin. Depending on your file you should read it in the most appropriate way- in my case, because I was trying to read a video, I read it as an arraybuffer.
Once read, you need to convert it to a blob (watch the syntax), and then the upload will run smoothly:
var file_path = "root/to/directory";
var name = "filename.mp4";
$cordovaFile.readAsArrayBuffer(file_path, name)
.then(function (success) {
// success
console.log(success);
blob = new Blob([success], {type: "video/mp4"});
console.log(blob);
var uploadTask = storageRef.child(name).put(blob);
uploadTask.on('state_changed', function(snapshot){
// Observe state change events such as progress, pause, and resume
// See below for more detail
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
}, function(error) {
// Handle unsuccessful uploads
console.log("Error uploading: " + error)
}, function() {
// Handle successful uploads on complete
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
var downloadURL = uploadTask.snapshot.downloadURL;
console.log("Success!", downloadURL);
});
}, function (error) {
// error
console.log("Failed to read video file from directory, error.code);
}
);
NB: 1) This refers to the web/javascript API - android and iOS APIs will be different. 2) Remember the file type may vary by device, so you need to handle this 3) I am using ngCordova, but the same applies to the regular cordova/phonegap plugin.
Hope you find this helpful.