The following code (inspired by the main answer of HTML5 Pre-resize images before uploading) takes the selected image file from the <input type="file">
, recompresses it to a JPG with quality 50% into the variable dataurl
.
Question: How to replace the content of the <input type="file">
by this newly-compressed file? So that when submitting the <form>
, it's this new file which will be submitted?
Note: I don't want to use AJAX for the upload, but the standard POST of the <form>
. The "posted" file should be dataurl
, i.e. it should be as if the file selected by the user in the <input type="file">
were the file generated by dataurl
.
function doit() {
var input = document.getElementById('file'),
canvas = document.getElementById('canvas');
var file = input.files[0];
var img = document.createElement("img");
var reader = new FileReader();
reader.onload = function(e) { img.src = e.target.result }
reader.readAsDataURL(file);
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataurl = canvas.toDataURL("image/jpeg", 0.5);
console.log(dataurl);
}
<form action="/upload" method="post">
<input type="file" onchange="doit();" id="file" /><br><br>
<input type="submit" />
</form>
<canvas id="canvas" style="display: none" />