Image Upload Preprocessing for HTML5,
When developing an H5 application,
The application only needs a small thumbnail,
However, a user uploads a large image via a mobile phone,
The number of pictures taken by the mobile phone camera is several MB, which wastes a lot of traffic.
Programmers who think about users like me will never let this happen,
So we have this article.
Get Image
Use the File API to retrieve images.
var input = document.createElement('input');input.type = 'file';input.addEventListener('change', function() { var file = this.files[0];});input.click();
Preview an image
UsecreateObjectURL()
OrFileReader
Preview an image
var img = document.createElement('img');img.src = window.URL.createObjectURL(file);
var img = document.createElement("img");var reader = new FileReader();reader.onload = function(e) { img.src = e.target.result;}reader.readAsDataURL(file);
Use canvas for thumbnails
var canvas = document.createElement("canvas");var ctx = canvas.getContext("2d");var MAX_WIDTH = 800;var MAX_HEIGHT = 600;var width = img.width;var height = img.height;if (width > height) { if (width > MAX_WIDTH) { height *= MAX_WIDTH / width; width = MAX_WIDTH; }} else { if (height > MAX_HEIGHT) { width *= MAX_HEIGHT / height; height = MAX_HEIGHT; }}canvas.width = width;canvas.height = height;ctx.drawImage(img, 0, 0, width, height);
Upload thumbnails
canvas.toBlob(function(blob) { var form = new FormData(); form.append('file', blob); fetch('/api/upload', {method: 'POST', body: form});});
Conclusion
DEMO: http://weekcool.com/js/upload.js
If you have any questions during the learning process or want to obtain learning resources, join the learning exchange group.
343599877. Let's learn the front-end together!