JSFiddle - React, Tailwind, and code Playground
HTML
<input type="file" id="imageUpload"/>
JavaScript
var file = document.getElementById('imageUpload');
var mime = "image/jpeg";
var max_width = 100;
var max_height = 100;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.onload = function () {
// Clear canvas, and resize image
ctx.clearRect(0, 0, max_width, max_height);
ctx.drawImage(img,
0, 0, img.width, img.height, // size of image
0, 0, max_width, max_height // size of canvas
);
// Get image from canvas as a dataURI, and convert to a blob object
var dataURI = canvas.toDataUrl(mime);
// Note: This function can be replaced with canvas.toBlob(),
// once supported by browsers.
// ---
var image_blob = (function () {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: mime});
})();
// ---
// Attach blob-object (contains our image) to form object
var form = new Form();
form.append("image", image_blob);
// Send AJAX request with multi-part data
var xhr = new XMLHttpRequest();
xhr.open('POST', '/route', true);
xhr.send(form);
// jQuery version
//$.ajax({
// type: "POST",
// url: "/route",
// data: form,
// processData: false,
// contentType: false
//})
//.done(function (response) {
// console.log(response);
//});
};
img.src = URL.createObjectURL(file);