Image Upload Preprocessing for HTML5,

Source: Internet
Author: User

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()OrFileReaderPreview 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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.