Upload base64 image with Ajax
I finally decided to convert the base64 image to a Blob so it can be sent via an Ajax request with the formData object as follows.It saves upload bandwidth (base64 takes 33% more bits than its binary equivalent) and I couldn't find the reason for no transmission of base64 parameter (due to size limitation somewhere for sure).
The base64ToBlob function is based on this answer to another question.
function base64ToBlob(base64, mime) { mime = mime || ''; var sliceSize = 1024; var byteChars = window.atob(base64); var byteArrays = []; for (var offset = 0, len = byteChars.length; offset < len; offset += sliceSize) { var slice = byteChars.slice(offset, offset + sliceSize); var byteNumbers = new Array(slice.length); for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } return new Blob(byteArrays, {type: mime});}
My JS code:
var url = "url/action"; var image = $('#image-id').attr('src');var base64ImageContent = image.replace(/^data:image\/(png|jpg);base64,/, "");var blob = base64ToBlob(base64ImageContent, 'image/png'); var formData = new FormData();formData.append('picture', blob);$.ajax({ url: url, type: "POST", cache: false, contentType: false, processData: false, data: formData}) .done(function(e){ alert('done!'); });
In Symfony2 I can retrieve the image thanks to:
$picture = $request->files->get('picture');
Nitseg's answer works nicely. Also, I wanted to add the following lines if you must use auth token in your ajax call. Again, take a look at Nitseg's answer for more details first.
var formData = new FormData();var token = "<YOUR-TOKEN-HERE>";formData.append("uploadfile", mediaBlob); jQuery.ajax({ url: url, type: "POST", cache: false, contentType: false, processData: false, data: formData, beforeSend: function (xhr){ xhr.setRequestHeader("Authorization", "Bearer " + token); }}).done((e) => { // It is done.}).fail((e) => { // Report that there is a problem!});