Angus Bremner Angus Bremner - 5 months ago 511
Javascript Question

Uploading image to Firebase Storage from Cordova app

I am trying to upload an image from my Cordova app to the new Firebase Storage. This is what I have attempted so far.



// Get the image from PhotoLibrary
navigator.camera.getPicture(onSuccess, onFail, {
quality: quality,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
destinationType: Camera.DestinationType.FILE_URI,
targetWidth: imageSize,
targetHeight: imageSize
});

function onSuccess(imageData) {

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

window.resolveLocalFileSystemURL(imageData,
function(fileEntry) {
fileEntry.file(function(file) {
var uploadTask = storageRef.child('images/test.jpg').put(file);
uploadTask.on('state_changed', function(snapshot){
console.log(snapshot);
});
}
)
};





This results in the following error

FirebaseError: Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.


One other thing I have tried is getting the image as base64 and converting to a Blob, but same result.

Does anyone one know how to get the image in the Javascript File or Blob formats that Firebase Storage requires? Thanks!

Answer

The link from Sam above led me in the right direction. Here is a working solution.

navigator.camera.getPicture(onSuccess, onFail, {
    quality: quality,
    sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
    destinationType: Camera.DestinationType.FILE_URI,
    targetWidth: imageSize,
    targetHeight: imageSize
});

function onSuccess(imageData) {

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

    var getFileBlob = function(url, cb) {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url);
        xhr.responseType = "blob";
        xhr.addEventListener('load', function() {
            cb(xhr.response);
        });
        xhr.send();
    };

    var blobToFile = function(blob, name) {
        blob.lastModifiedDate = new Date();
        blob.name = name;
        return blob;
    };

    var getFileObject = function(filePathOrUrl, cb) {
        getFileBlob(filePathOrUrl, function(blob) {
            cb(blobToFile(blob, 'test.jpg'));
        });
    };

    getFileObject(imageData, function(fileObject) {
        var uploadTask = storageRef.child('images/test.jpg').put(fileObject);

        uploadTask.on('state_changed', function(snapshot) {
            console.log(snapshot);
        }, function(error) {
            console.log(error);
        }, function() {
            var downloadURL = uploadTask.snapshot.downloadURL;
            console.log(downloadURL);
            // handle image here
        });
    });

}

Comments