Skip to content

Instantly share code, notes, and snippets.

@bbottema
Created September 30, 2015 18:19
Show Gist options
  • Save bbottema/3427990d350c622a7489 to your computer and use it in GitHub Desktop.
Save bbottema/3427990d350c622a7489 to your computer and use it in GitHub Desktop.
Complete example using FormData to post a variable and file to a service and parsing the binary result to base64
var formData = new FormData();
formData.append("user", "Mario");
formData.append("testdot", imgData);
createRequest("POST", "some webservice", callback).send(formData);
/*
* SOLUTION 1
*/
function callback(file) {
var reader = new FileReader();
reader.onload = function(event) {
$("body").append($('<img/>', { src: event.target.result }));
};
reader.readAsDataURL(new Blob([file], {type: 'image/png'})); // will give base64 string
};
/*
* SOLUTION 2
*/
function callback(file) {
$("body").append($('<img/>', { src: "data:image/png;base64, " + arrayBufferToBase64(file) }));
};
function arrayBufferToBase64(buffer) {
return window.btoa(readBinaryDataToString(buffer));
}
function readBinaryDataToString(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return binary;
}
/*
* AJAX to read binary data
*/
function createRequest(method, url, callback) {
var xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.responseType = "arraybuffer";
xhr.onreadystatechange = function(evt) {
// use `xhr` and not `this`... thanks IE
if (xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 0) {
try {
callback(null, xhr.response || xhr.responseText);
} catch (e) {
callback(new Error(e), null);
}
} else {
callback(new Error("Ajax error for : " + this.status + " " + this.statusText), null);
}
}
};
return xhr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment