toDataURL的输出是base64,如何减少1/3的上传时间和带宽? [英] toDataURL's output is base64, how to reduce the uploading time and bandwidth of a factor 1/3?
问题描述
以下代码的目标是压缩输入文件(2 MB JPG文件=> 500 KB文件),然后在提交< form> $ c $时将其上传到服务器c>。
The goal of the following code is to compress the input file (2 MB JPG file => 500 KB file) and then upload it to server when submitting the <form>
.
将图像从JPG文件导入画布,然后使用 toDataURL
with:
When importing an image from a JPG file into a canvas, and exporting it with toDataURL
with:
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>
隐藏字段>是base64编码的,例如:
it works, but the output hidden
field in the <form>
is base64-encoded, i.e. something like:
data:image/jpeg;base64,/9j/4AAQSkZJRgAB...
众所周知,base64使用正常大小的二进制数据的1.3333倍。
It is well known that base64 uses 1.3333 times the normal size of binary data.
问题:在这种情况下如何避免浪费上传时间(客户端=>服务器)和带宽的1/3数据,即提交<时; form>
?
Question: how to avoid to waste 1/3 of data in uploading time (client => server) and bandwidth in this case, i.e. when submitting the <form>
?
注意:如果我使用AJAX而不是<$ c $,我认为问题会是一样的c>< form> 提交,不是吗?
Note: I think the problem will be the same if I use AJAX instead of <form>
submission, isn't it?
推荐答案
var jsForm = null;
function doit() {
var file = document.getElementById('file').files[0],
canvas = document.getElementById('canvas'),
ctx = canvas.getContext("2d"),
img = document.createElement("img");
img.src = window.URL.createObjectURL(file);
img.onload = function () {
if (!jsForm) {
jsForm = new FormData();
}
ctx.drawImage(img, 0, 0);
canvas.toBlob(function(blob) {
jsForm.set('image', blob, file.name);
}, "image/jpeg", 0.5);
}
}
var form = document.getElementById('form');
form.onsubmit = function(e) {
e.preventDefault();
if (!jsForm) return;
var request = new XMLHttpRequest();
request.open(this.method||'POST', this.action||'/');
request.send(jsForm);
jsForm = null;
}
<form method="POST" action ="/upload" id="form">
<input type="file" onchange="doit();" id="file" />
<button>Submit</button>
</form>
<canvas id="canvas" style="display: none" />
这篇关于toDataURL的输出是base64,如何减少1/3的上传时间和带宽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!