Robin Robin - 15 days ago 7x
AngularJS Question

Create Javascript File/Blob object from image URI

Is it possible to create a File or Blob object for my image out of an image URI?

Using Cordova Image Picker, a plugin on my mobile app, I can retrieve photo URI's that look like this: "file:///data/user/0/..../image.jpg"

However, I am now trying to create a File or Blob object which Google Firebase requires for my images to be uploaded. I just can't figure out how. Every solution I try seems to be wrong to the point where I think I'm looking at it from a complete wrong perspective. I'm new to Javascript. Thanks a lot!


Have a look at a question that I posted a while back which deals with this but for videos (same principle applies): Uploading video to firebase (3.0) storage using cordovaFileTransfer

You need to read as an arrayBuffer using cordova's file plugin, then blob; something like:

var file_path = "root/to/directory";
var name = "filename.jpg";

                $cordovaFile.readAsArrayBuffer(file_path, name)
                    .then(function (success) {
                        // success

                      blob = new Blob([success], {type: "image/jpeg"});


                      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:
                        var downloadURL = uploadTask.snapshot.downloadURL;
                        console.log("Success!", downloadURL);

                      }, function (error) {
                        // error
                        console.log("Failed to read file from directory, error.code);


If your program passes you a full path to the image you will need to separate the name from the path to the directory where the image is stored. Just look for everything after the final /