HTML5: file upload and download,

Source: Internet
Author: User

HTML5: file upload and download,

Website ConstructionIn, file upload and download are inevitable. The APIS provided in HTML5 have a wide range of applications at the front end, which perfectly solves the compatibility issues of various browsers. So hurry up and get it!

FileList object and file object

The input [type = "file"] tag in HTML has a multiple attribute that allows you to select multiple files. The FileList object indicates the list of files selected by the user. Each file in this list is a file object.

File object attributes:

  • Name: file name, excluding the path.

  • Type: file type. Image files start with image/. Therefore, only images can be uploaded.

  • Size: file size. You can perform other operations based on the file size.

  • LastModified: The last modification time of the file.

<Input type = "file" id = "files" multiple> <script> var elem = document. getElementById ('files'); elem. onchange = function (event) {var files = event.tar get. files; for (var I = 0; I <files. length; I ++) {// the file type is image and the file size is smaller than kb if (files [I]. type. indexOf ('image /')! ==- 1 & files [I]. size <204800) {console. log (files [I]. name) ;}}</script>

Input has an accept attribute, which can be used to specify the file type that can be submitted through file upload.

Accept = "image/*" can be used to restrict the upload of only image formats. However, a slow response occurs in the Webkit browser. The file selection box will only pop up several seconds later.

The solution is to change * to the specified MIME type.

<input type="file" accept="image/gif,image/jpeg,image/jpg,image/png">
Blob Object

A Blob Object is equivalent to a container and can be used to store binary data. It has two attributes: The size attribute indicates the length of bytes, And the type attribute indicates the MIME type.

How to create

Blob objects can be created using the Blob () constructor.

var blob = new Blob(['hello'], {type:"text/plain"});

The first parameter in the Blob constructor is an array that can store ArrayBuffer objects, ArrayBufferView objects, Blob objects, and strings.

Blob objects can return a new Blob Object through the slice () method.

var newblob = blob.slice(0,5, {type:"text/plain"});

The slice () method uses three parameters, which are optional. The first parameter indicates that the replication starts from the starting position of the binary data in the Blob object, the second parameter indicates the end position of the replication, and the third parameter indicates the MIME type of the Blob Object.

Canvas. toBlob () can also be used to create Blob objects. ToBlob () uses three parameters. The first is the callback function, the second is the image type, the default is image/png, and the third is the image quality. The value ranges from 0 to 1.

var canvas = document.getElementById('canvas');canvas.toBlob(function(blob){ console.log(blob); }, "image/jpeg", 0.5);
Download files

The Blod object can generate a network address through the window. URL object and download the object based on the download attribute of tag.

For example, you can download a canvas as an image file.

Var canvas = document. getElementById ('canvas '); canvas. toBlob (function (blob) {// use createObjectURL to generate an address in the format of blob: null/fd95b806-db11-4f98-b2ce-5eb16b38ba36 var url = URL. createObjectURL (blob); var a = document. createElement ('A');. download = 'canvas ';. href = url; // simulate a tag and click to download. click (); // After downloading, tell the browser that the File Reference URL is no longer needed. revokeObjectURL (url );});

You can also save the string as a text file in a similar way.

FileReader object

The FileReader object is mainly used to read files into the memory and read data in files. Create a FileReader object using the constructor

var reader = new FileReader();

This object has the following methods:

  • Abort: The read operation is interrupted.

  • ReadAsArrayBuffer: Read the file content to the ArrayBuffer object.

  • ReadAsBinaryString: reads binary data from a file.

  • ReadAsDataURL: reads a file as a string in data: URL format.

  • ReadAsText: Read the file as text.

Upload image Preview

A common application is to use readAsDataURL () to display images after uploading images on the client.

<input type="file" id="files" accept="image/jpeg,image/jpg,image/png"><script>    var elem = document.getElementById('files'),        img = document.getElementById('preview');    elem.onchange = function () {        var files = elem.files,            reader = new FileReader();        if(files && files[0]){            reader.onload = function (ev) {                img.src = ev.target.result;            }            reader.readAsDataURL(files[0]);        }    }</script>

However, a bug may occur when you upload a picture while taking a picture vertically on some mobile phones, and you will find that the picture has fallen, including Samsung and iPhone... The solution is not described here. If you are interested, you can view the solution for rotating and compressing uploaded images on mobile devices.

Data backup and recovery

The readAsText () of the FileReader object can read the file text. Combined with the download function of the Blob object, the exported data file can be backed up to the local device. when the data is to be restored, upload the backup file through input, read the text using readAsText (), and restore data.

The code is similar to the above function. It is not repeated here. For specific applications, refer to notepad.

Base64 encoding

Added the atob and btoa methods in HTML5 to support Base64 encoding. Their names are also very simple. B to a and a to B represent encoding and decoding.

var a = "https://lin-xin.github.io";var b = btoa(a);var c = atob(b);console.log(a);     // https://lin-xin.github.ioconsole.log(b);     // aHR0cHM6Ly9saW4teGluLmdpdGh1Yi5pbw==console.log(c);     // https://lin-xin.github.io

The btoa method encodes string a without changing the value of a and returns an encoded value.
The atob method decodes the encoded string.

However, if the parameter contains Chinese characters and exceeds the 8-bit ASCII character range, the browser reports an error. Therefore, encodeURIComponent encoding must be performed for Chinese characters.

Var a = "Hello World"; var B = btoa (encodeURIComponent (a); var c = decodeURIComponent (atob (B); console. log (B); // JUU1JTkzJTg4JUU1JTk2JUJEJTIwJUU0JUI4JTk2JUU3JTk1JThDconsole. log (c );

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.