Introduction to HTML5 's File API usage

Source: Internet
Author: User
Tags error code


The purpose of the File API is to provide Web developers with a secure way to access files on the user's computer and to perform operations on them better.

HTML5 Although it allows us to access the local file system, files can only be read to the file API if the user triggers the read behavior, which usually occurs when the form file is selected and dragged.

I. Compatibility of the File API

The File API support in major mainstream browsers is shown in the following illustration:


Note: Pictures reproduced from: http://www.ibm.com/developerworks/cn/web/1210_jiangjj_html5log/

More detailed information about the browser's support for the File API can be referred to the website http://caniuse.com/#search =file.

You can use the following method to detect whether the current browser supports the file API:

function Checksupportfileapi () {
if (window. File && window. FileList && windows. FileReader) {
return true;
} else {
return false;
}
}
Two. Properties of the File object

Fileapi the file input fields in the form, and adds some interfaces that directly access the file information. HTML5 adds a file collection to the document INPUT element in the DOM. When you select one or more files from a file input field, the file collection contains a set of file objects, each of which corresponds to one. Each file object has the following read-only properties:

Name: The filename of the local file system;
Size: The byte size of the file;
Type:string type, MIME type of file;
Lastmodifieddate:string type, the last time the file was modified.
In HTML5, by adding the Multiple property, multiple files are allowed to be placed at once in the file control. Each of the selected files within the control is a file object.

Example: By listening for the change event and reading the Files collection, you can know each file's information:

<input type= "file" name= "" id= "Fileslist" multiple>

<script type= "Text/javascript" >
var fileslist = document.getElementById ("Fileslist");
Fileslist.addeventlistener ("Change", function (e) {
var files = this.files,
i = 0,
len = 0;
if (files) {
len = files.length;
}
while (I < Len) {
Console.log (Files[i].name + "(" + Files[i].type + "," + files[i].size + bytes) ");
i++;
}
});
</script>
When three files are selected, the output in the console is as follows:

A.jpg (Image/jpeg, 1499704bytes)
B.png (Image/png, 395511bytes)
C.jpg (Image/jpeg, 1614001bytes)
Three. FileReader Object

3.1 FileReader method of reading file data

The FileReader type implements a file-reading mechanism. You can think of FileReader as XMLHttpRequest, except that it reads the file system, not the remote server. FileReader provides an asynchronous API that allows you to access the file system asynchronously in the main browser thread and read the data in the file. To read the data in the file, FileReader provides the following methods:

Readastext (File|blob [, encoding]): reads the file as plain text and saves the read text in the result property. The second parameter is used to specify the encoding type, optional.
Readasdataurl (FILE|BLOB): reads the file and saves the file as a data URI in the result property.
Readasbinarystring (FILE|BLOB): reads a file and saves a string in the result property, and each character in the string represents one byte.
Readasarraybuffer (FILE|BLOB): reads the file and saves a arraybuffer containing the contents of the file in the result property.
Abort (): interrupt read operation.
These methods of reading files provide a great convenience for flexible processing of file data. For example, you can read an image file and save it as a data URI, display it to the user over time, or, for ease of resolution, read the file as text.

Compatibility of 3.2 FileReader

All browsers that implement FILEAPI support the Readastext () and Readasdataurl () methods. However, IE10 PR 2 does not support readasbinarystring () and Readasarraybuffer (). The FileReader API is not supported by IE9 and the following versions of browsers.

The method for checking whether the current browser supports the FileReader API is as follows:

if (typeof FileReader = = "undefined") {
Alert ("Your browser does not support the FileReader API.");
} else {
var reader = new FileReader ();
}
The events of 3.3 FileReader

Because the process of reading a file is asynchronous, FileReader also provides several events that are commonly used:

Progress (): in Data reading.
Error (): triggered when a data read error occurs.
Load (): triggered when data read completes successfully.
Abort (): Triggered when data read is interrupted.
Loadstart (): triggered when data reads start.
Loadend (): Triggers when data reads complete, whether successful or unsuccessful.
Every 50ms or so, a progress event is triggered back. The event object enables you to obtain the same information (properties) as the XHR Progress event: Lengthcomputable, Loaded, and total. The contents of the file can be read in each progress event through the FileReader result property.

An error event is triggered when a file cannot be read. When an error event is triggered, the relevant information is saved to the FileReader error property. This property will hold an object that has only one property code, the error code. The attribute values for this error code are as follows:

1: File not found;
2: Indicates security error;
3: Read interrupt;
4: The file is not readable;
5: Encoding error.
The Load event is triggered when the file is successfully loaded. If an error event occurs, the Load event does not occur.

Example:

<input type= "file" name= "" id= "Fileslist" >
<div id= "Progress" ></div>
<div id= "Output" ></div>

<script type= "Text/javascript" >
var fileslist = document.getElementById ("Fileslist");
Fileslist.addeventlistener ("Change", function (e) {
var info = "",
Output = document.getElementById ("Output"),
progress = document.getElementById ("Progress"),
Files = this.files,
Type = "Default",
reader = new FileReader ();

if (/image/.test (Files[0].type)) {
Reader.readasdataurl (Files[0]);
Type = "image";
} else {
Reader.readastext (Files[0]);
Type = "Text";
}

Reader.onerror = function () {
output.innerhtml = "Error code:" + Reader.error.code;
};
reader.onprogress = function (event) {
Console.log ("lengthcomputable:" + event.lengthcomputable);
if (event.lengthcomputable) {
progress.innerhtml = event.loaded + "/" + event.total;
}
};
Reader.onload = function () {
var html = "";
Switch (type) {
Case "image":
html = "Break
Case "Text":
html = reader.result.toString ();
Break
}
output.innerhtml = html;
}
});
</script>
In this case, reads the selected file in a form field and displays its contents on the page if it is a picture type of file, it is saved as a data URI, and the content is read and displayed as a string, if it is a file instead of a picture.

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.