Skip to content

Instantly share code, notes, and snippets.

@shaoner
Last active October 13, 2015 12:01
Show Gist options
  • Save shaoner/cad3dce08c270ce10b89 to your computer and use it in GitHub Desktop.
Save shaoner/cad3dce08c270ce10b89 to your computer and use it in GitHub Desktop.
Ionic upload from base64 encoded image
angular.module('myapp.image', [ ])
.factory('Image', function ($http) {
function blobFromDataURI(dataURI) {
var raw = window.atob(dataURI.replace(/[^,]+,/, '')),
imgBuffer = [];
for (var i = 0, len = raw.length; i < len; i++) {
imgBuffer.push(raw.charCodeAt(i));
}
return new window.Blob([ new Uint8Array(imgBuffer) ],
{ type: 'image/jpeg' });
}
function formData(name, dataURI) {
var fd = new window.FormData();
fd.append(name, blobFromDataURI(dataURI));
return fd;
}
return {
upload: function (url, dataURI) {
return $http.post(url, formData(dataURI), {
// This will define the Content-Type to 'multipart/form-data'
// with an appropriate boundary
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
});
}
};
});
@shaoner
Copy link
Author

shaoner commented Oct 13, 2015

Example:

Image.upload('http://somewhere.tld/image', 'data:image/jpg;base64,/9j/4AAQSkZJRg...');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment