HTML 5 learning notes on file reading

Source: Internet
Author: User
Tags error code file size

The file API in HTML 5 is a big bright spot in HTML 5 that lets us read local files. Let all developers sigh! Multiple Access file interfaces are provided through the file API specification.

Browser support for file-related interfaces in HTML 5

When using the file API, you may need to detect browser support, and the feature detection code is as follows:

Copy
Detects if the browser supports the file API-related interfaces.
if (window. File && window. FileReader && windows. FileList && windows. Blob) {
Support Drop
} else {
does not support
Alert (the ' HTML5 File API is not fully supported in your browser. ');
}
The file API in the browser cannot read files without the ability to read them, and you must use the user's behavior to trigger the reading of the file. For example, when a user clicks on a Web page, the file API is used to get information about the files. Browsers that support the file API are ie10+, FireFox 3.5+, Opera 10.6+, Safari 5+, Chrome and iOS versions of Safari and Android WebKit, UC, of course, most of them are not fully supported.

Related description of the file object

In browsers, because of security restrictions, a file object typically obtains an FileList array by clicking on the Type=file input form, HTML 5 's drag-and-drop API, and containing one or more file objects when pasted into the input box. The file object contains information about files such as file names, file sizes, file types, and so on.

Object Type description
A file-independent object that contains mainly the following properties: Name, size, type, lastmodifieddate, and Slice () method (can be directly converted to an object URL or read via the FIL API)
FileList a sequence of class arrays of a file object (sometimes appears when the files are multiple-selected)
A blob Blob object is a parent type of the file type, and is a file object that reads part of the entire file through the slice () method. The BLOB type has two attributes of size, type, and of course, the slice () method is supported
The above properties are briefly described below:

Name: file name in the local file system
Size: Sizes of files, in bytes
Type: MIME type of file (string)
LastModifiedDate: File Last Modified time, string (Chrome only supported)
The following is a simple example that selects a file through form file and then displays the relevant information about the file, the following code:

HTML Code:

Copy
<!--start: Input form-->
<input type= "File" name= "file" multiple/>
<!--end: Enter form-->
<!--start: template-->
<div class= "Remark" >
<p> file name:<!--name--></p>
<p> File size:<!--size--> byte</p>
<p> file type:<!--type--></p>
<p> file Last modified time:<!--lastmodifieddate--></p>
</div>
<!--end: template-->
JavaScript Code:

Copy
if (!) ( Window. File && window. FileReader && windows. FileList && windows. Blob)) {
Alert (' Your browser does not fully support the FileReader API interface, please try using a browser that supports HTML 5! ');
throw new Error (' Browser not support File API ');
}

/**
* * Parse template file
* @param template Template string
* @param scope Template Scope
* return [string] parsed string
*/
function Templateparse (template, scope) {
if (typeof template!= "string") return;
Return Template.replace (/<!--\w+--\>/gi, function (matchs) {
var returns = Scope[matchs.replace (<!--) | ( --\>)/g, "")];
Return (returns + "") = = "undefined"? "": Returns;
});
}

Window.addeventlistener (' Load ', function () {
var Inputfield = document.queryselector (' input[name= ' file '] '),//form input Box
Remark = Document.queryselector (' Div.remark '),
template = remark.innerhtml; Template file

Inputfield.addeventlistener (' Change ', function () {
var files = this.files,i= 0, t = "";
for (;i<files.length; i++) {
T + + templateparse (template, files[i]);
}
remark.innerhtml = t;
},false);
}, False);
FileReader type

When used in conjunction with the above data structure, FileReader can use JavaScript events to handle asynchronous read files. Because you can monitor read progress, identify errors, and determine when the load completes. There are many similarities between FileReader and the XMLHttpRequest event model. The difference is that with the FileReader is read the local file, and XMLHttpRequest is used to read the files on the server. The following is a simple code that describes the file type files:

The FileReader type implements a way to read files asynchronously, and provides several methods:

Readastext (file, [encoding]): reads files as a plain file and saves the text that is fetched in the result property of the instance object. The second parameter represents the type of encoding to read, optional
Readasdataurl (file): Read files and save data as data URL in the instance object result property, such as SRC that can be directly assigned to the picture (will be converted to base64 encoding)
Readasbinarystring (file): Reads files and saves a string in the result property, each character in the string represents one byte (not implemented in IE 10)
Readasarraybuffer (file): reads the files and saves a arraybuffer containing the contents of the file in the result attribute (not implemented in IE 10)
Abort (): Terminates the current read operation
Because the process of reading a file is asynchronous, FileReader also provides the appropriate event handling, as follows:

Progress: Typically used to track the progress of current file reads, which are normally triggered every 50ms or so during the reading of a file. The event object allows you to obtain the same information as the XHR Progress event: Lengthcomputable, Loaded, and total.
Error: The callback function that generates an error during the reading process; If an error event occurs, then the load event is not generated. The error event is triggered, and the relevant information is saved to the FileReader error property, which is an object with only one property code, error code: 1, File not found, 2, security error 3, read interrupted, 4, file unreadable.
Load: Callback When file read is successful
Loadstart: Callback When starting to read files
Abort: Callback When the read file operation is terminated
Loadend: Callback when file reads complete (note: This event is executed regardless of whether the file reads successfully or fails)

Read part of a file

Sometimes, we need to use the slice () method of the file object in order to read part of the document rather than all of it. The implementation of this method in Firefox is called Mozslice (), which is called Webkitslice () in Chrome. The slice () method receives two parameters, the starting byte and the byte to be read, and the method returns a BLOB instance. The following is a generic handler function:

Copy
function Blobslice (blob, startbyte, length) {
if (Blob.slice) {
Return Blob.slice (startbyte, length);
else if (Blob.webkitslice) {
Return Blob.webkitslice (startbyte, length);
else if (Blob.mozslice) {
Return Blob.mozslice (startbyte, length);
} else {
return null;
}
}
The BLOB type has a size property and a Type property, and there is also a slice () method, because we can continue to cut the data. FileReader can also read data from a blob, as shown in the following example (to select a file larger than 32B):

HTML Code:

Copy
<label for= "Text" > Please select File <input type= "file" id= "text" name= "text" accept= "text/*"/></label>
<p id= "Textremark" > Temporarily no content </p>
Js Code:

Copy
Window.addeventlistener (' Load ', function () {
var textInput = document.queryselector (' input[name= ' text "]");
Textinput.addeventlistener (' Change ', function () {
var files = this.files[0],
reader = new FileReader (),
Blob = blobslice (files, 0, 32),
Textremark = Document.queryselector (' P#textremark ');
if (BLOB) {
Reading files
Reader.readastext (BLOB);
Read error
Reader.addeventlistener (' Error ', function () {
textremark.innerhtml = ' Read error code: ' + Reader.error.code;
},false);
Read succeeded
Reader.addeventlistener (' Load ', function (e) {
textremark.innerhtml = This.result;
},false);
} else {
Alert (' Your browser does not support the slice method ');
}
},false);
},false);
Object URL

The object URL, also known as a blob URL, refers to a URL that references data saved in a file or blob. The advantage of using object URLs is that we do not need to call file reader to read the corresponding data. To create an object URL, you can use window. Url.createobjecturl () method to create and pass in a file or Bolb object. Its compatible processing schemes are as follows:

Copy
function Createobjecturl (BLOB) {
if (window. URL) {
return window. Url.createobjecturl (BLOB);
}else if (window.webkiturl) {
Return Window.webkitURL.createObjectUrl (BLOB);
}else {
return null;
}
}
The following is an example that is inserted into the IMG tag through a blob:

HTML code

Copy
<label for= "ImageList" > Please select File <input type= "file" id= "imageList" multiple name= "image" accept= "image/*"/> </label>
<p id= "Imageremark" > Temporarily no content </p>
JS Code

Copy
Window.addeventlistener (' Load ', function () {
var imageList = document.getElementById (' imageList '),
Imageremark = document.getElementById (' Imageremark ');

Imagelist.addeventlistener (' Change ', function (e) {
if (!this.files.length) return;

var url = null,
i= 0,
L=this.files.length,
html = ';
for (; i<l;i++) {
url = Createobjecturl (This.files[i]);
if (URL) {
html+= ' ';
}
url = null;
}

imageremark.innerhtml = html;

},false);
},false);
The above code, in fact, directly read the picture file into memory, and then create an object URL to form an in-memory reference. Directly into the IMG tag, compared with filereader, the efficiency is indeed much higher. However, because the file read is placed in memory, if there is a reference to the picture, then the memory occupied by the picture will not be released. To manually erase the memory, you can pass the object URL as a parameter to Window.URL.revokeObjectURL () directly. Because the prefixes in different browsers are different, the following compatibility functions are available:

Copy
function Revokeobject (URL) {
if (window. URL) {
Window. Url.revokeobjecturl (URL);
else if (Window.webkiturl) {
Window.webkitURL.revokeObjectURL (URL)
}
}


In general, the memory occupied by the object URL is automatically released after the page is unloaded. But sometimes, in order to release memory in time, you can use the above method

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.