Reputation: 143
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!
Upvotes: 0
Views: 1928
Reputation: 190
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
console.log(success);
blob = new Blob([success], {type: "image/jpeg"});
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 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 /
Upvotes: 2