(888) 685-3101 ext. 2

The following requires some HTML5 features, so be sure to consult a compatibility chart before throwing it into a customer’s environment.

I needed a way for a user to upload an image as a base64 string. This could be happening from a poor bandwidth connection, so the usual server-side resize/encode wasn’t going to be an option. After a little bit of research my proof of concept looked like this.

I didn’t see any other examples of this so I thought I would post it here.


// make the file upload utility on page load
var photoField = dojo.byId("photoDiv");
var fu = document.createElement('input');
fu.type = "file";
fu.accept = "image/jpg,image/jpeg";
fu.id = "fuContactPhoto";
fu.onchange = photoConvert;
photoField.appendChild(fu);

function photoConvert() {
var fu = document.getElementById("fuContactPhoto"); // grab the file browser
var f = fu.files[0]; // grab the file
var fr = new FileReader(); // create a new file reader
fr.readAsDataURL(f); // base 64 it
fr.onload = function() {
var tempImage = new Image();
tempImage.src = fr.result; // to get the base64 result
setTimeout(function() { // adding a .2 second delay because of some strange timing problems on ios
var height = tempImage.height;
var width = tempImage.width;
if (height > 100) { // max height for our purposes is 100 pixels
width = width / (height / 100);
height = 100;
}
if (width > 150) { // max width for our purposes is 150 pixels
height = height / (width / 150);
width = 150;
}
var c = document.createElement('canvas');
c.width = width;
c.height = height;
var ctx = c.getContext("2d");
ctx.drawImage(tempImage, 0, 0, width, height);
var b64str = c.toDataURL("image/jpeg"); // grab a base64 copy of the resized image as a jpeg
document.getElementById('photoBase64Value').value = b64str.replace("data:image/jpeg;base64,", ""); // set hidden field with our value to save
}, 200);
};
}

Share This