I'm trying to compress images from the client side before uploading to the server. My goal is to capture the image in a file input, Compress it, and then add the compressed image as a value in another file input field(ImageInput) which will be submitted to the server in a POST.
The Image is being compressed, But ImageInput input does not get the value of the image. It posts an empty image
<script>
function process() {
const file = document.querySelector("#upload").files[0];
if (!file) return;
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (event) {
const imgElement = document.createElement("img");
imgElement.src = event.target.result;
imgElement.onload = function (e) {
const canvas = document.createElement("canvas");
const MAX_WIDTH = 400;
const scaleSize = MAX_WIDTH / e.target.width;
canvas.width = MAX_WIDTH;
canvas.height = e.target.height * scaleSize;
const ctx = canvas.getContext("2d");
ctx.drawImage(e.target, 0, 0, canvas.width, canvas.height);
const srcEncoded = ctx.canvas.toDataURL(e.target, "image/jpeg");
// you can send srcEncoded to the server
alert(srcEncoded)
document.querySelector("#output").src = srcEncoded;
// my file input which I want to give a value of the compressed image
document.getElementById('ImageInput').value = srcEncoded;
};
};
}
</script>