'Upload Multiple Resized Images Using Javascript (jQuery)
I have put together this code from different sources, it works if I remove the resizing code. I am able to upload multiple files using the for loop as it is, but unable to grasp the resizing technique. I suspect there is something to do with the file reader. How to fix the resizing part? Thanks.
Here is the JavaScript part:
function fileToDataUri(field) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.addEventListener("load", () => {
resolve(reader.result);
});
reader.readAsDataURL(field);
});
}
function resizeImage(imgToResize, resizingFactor = 0.3) {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
const originalWidth = imgToResize.width;
const originalHeight = imgToResize.height;
const canvasWidth = originalWidth * resizingFactor;
const canvasHeight = originalHeight * resizingFactor;
canvas.width = canvasWidth;
canvas.height = canvasHeight;
context.drawImage(imgToResize, 0, 0, originalWidth * resizingFactor, originalHeight * resizingFactor );
return canvas.toDataURL();
}
function uploadImage() {
var input_files = document.getElementById('input_images');
var form = new FormData();
for (i = 0; i < input_files.files.length; i++) {
// RESIZE
var file = input_files.files[i];
var original_image = new Image();
original_image.src = fileToDataUri(file);
var resized_image = new Image();
resized_image.src = resizeImage(original_image);
// UPLOAD
form.append("image", resized_image);
var settings = {
"url": "my-api-url",
"method": "POST",
"timeout": 0,
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": form
};
$.ajax(settings).done(function (response) {
//console.log(response);
var jx = JSON.parse(response);
console.log(jx.data.url);
document.getElementById("uploaded_images").innerHTML = document.getElementById("uploaded_images").innerHTML + "<br><div><img src='" + jx.data.url + "'> " + jx.data.url + "</div>";
});
}
}
The HTML part:
<input type="file" accept="image/*" name="input_images" id="input_images" multiple>
<input type="button" value="Upload" onclick="uploadImage();">
<div id="uploaded_images"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
