How to replace a file input's content by the result of canvas.toDataURL?

form-submit, forms, html, html5-canvas, javascript

Solution

It seems we cannot modify the `<input type="file">`, but we can add the data to another text field (as advised by @PatrickEvans) or an `<input type="hidden">`:

function doit() {
    var file = document.getElementById('file').files[0],
        canvas = document.getElementById('canvas'),
        hidden = document.getElementById('hidden'),
        ctx = canvas.getContext("2d"),
        img = document.createElement("img"),
        reader = new FileReader();  
    
    reader.onload = function(e) { 
        img.src = e.target.result;
    }
    
    img.onload = function () { 
        ctx.drawImage(img, 0, 0);
        hidden.value = canvas.toDataURL("image/jpeg", 0.5);
    }
    reader.readAsDataURL(file);
}
<input type="file" onchange="doit();" id="file" />

<form action="/upload" method="post">
<input type="hidden" id="hidden" />
<input type="submit" />
</form>

<canvas id="canvas" style="display: none" />

The output `hidden` field in the `<form>` is base64-encoded, i.e. something like:

data:image/jpeg;base64,/9j/4AAQSkZJRgAB...

Problem

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" /> ```

Original source

Related problems