如何用 canvas.toDataURL 的结果替换文件输入的内容?
以下代码(灵感来自 HTML5 Pre-resize images before uploading) 从 <input type="file">
中获取选定的图像文件,将其重新压缩为质量为 50% 的 JPG 到变量 dataurl
.
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
.
问题:如何用这个新压缩的文件替换<input type="file">
的内容?这样在提交<form>
的时候,这个新文件会被提交吗?
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?
注意:我不想使用 AJAX 进行上传,而是使用 <form>
的标准 POST.posted"文件应该是dataurl
,即用户在<input type="file">
中选择的文件应该是文件由 dataurl
生成.
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" />
推荐答案
好像不能修改<input type="file">
,但是可以将数据添加到另一个文本中字段(由@PatrickEvans 建议)或 <input type="hidden">
:
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" />
<form>
中的输出 hidden
字段是 base64 编码的,例如:
The output hidden
field in the <form>
is base64-encoded, i.e. something like:
data:image/jpeg;base64,/9j/4AAQSkZJRgAB...
相关文章