and in my case, I just can choose to get image file from it's URI.
We don't have "[Select file...]" button to click to set our file directly into $scope object.
For example:
$scope.insertFile = function (file) {
$scope.fileObject = file;
};
I then use Cordova's plugin, $cordovaFile - readAsDataURL, to get the base64 formatted file.
It's so I can upload my picture through $http and data parameter in form of FormData().
Simply convert into Blob as below does not work:
$cordovaFile.readAsDataURL(file.directory, file.name).then(function(response) {
// take jpeg image as example
var imageFile = new Blob(response, {type: 'image/jpeg'});
formData.append('photo', imageFile, file.name);
};
It (the conversion) breaks my image file, because `new Blob()` doesn't automatically encode base64.
I have been struggling to get a non-broken image uploaded for some time until I found a solution that solved my problem below.
Solution
I found a useful HTML5 Filesystem API library code has method that helps correctly converting base64 into Blob.
With this I corrected my code into:
$cordovaFile.readAsDataURL(file.directory, file.name).then(function(response) {
// take jpeg image as example
var imageFile = dataURLToBlob(response);
formData.append('photo', imageFile, file.name);
};
It does convert my image file correctly, and my app is no longer uploading broken image again.
Reference:
http://stackoverflow.com/questions/12168909/blob-from-dataurl
No comments:
Post a Comment
Hey, thank you for spending time leaving some thoughts, that would be really helpful as encouragement for us to write more quality articles! Thank you!