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

╄→гoц情女王★ 提交于 2019-12-23 05:46:07

问题


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

回答1:


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...


来源:https://stackoverflow.com/questions/51052731/how-to-replace-a-file-inputs-content-by-the-result-of-canvas-todataurl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!