Todataurl's Output Is Base64, How To Reduce The Uploading Time And Bandwidth Of A Factor 1/3?
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
Solution 1:
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" />
Post a Comment for "Todataurl's Output Is Base64, How To Reduce The Uploading Time And Bandwidth Of A Factor 1/3?"