In the previous articles, I shared several HTML5 examples with you, including drag-and-drop function demonstration, page content editable demonstration and local storage function demonstration. Today, I will share with you a simple application to demonstrate how to use FileReader. FileReader is a file operation API provided in HTML5.
When you were looking at the HTML 5 example I wrote earlier, I was thinking about creating a simple but applicable example to practice these new HTML5 features in a more novel way. My goal is not to simply demonstrate these HTML 5 APIs, but to use examples to show developers how to actually implement these APIs in a practical and innovative way.
In HTML5, accessing the local file system from a Web page becomes very simple, that is, using the File API. This File specification provides an API to represent file objects in web applications. You can select them and access their information programmatically. This File API includes:
A FileList sequence, representing an array composed of individual files selected in the local system. The user interface for selecting files can be implemented by calling .
A Blob interface, which represents raw binary data. Through the Blob object, you can access the byte data inside.
A File interface, which stores read-only attribute information of the file, such as file name, file type, and file data access address.
A FileReader interface, which provides methods for reading a file and an event model for obtaining file reading results.
A FileError interface and a FileException object, which are used to define the error conditions in this specification.
How to use this example: In this example, I have given an artboard, and you can drag an image into it from the local file system, or you can also use the file selection box to select an image. In the example, please only select image files, I did not add file filtering and file type checking. Please keep in mind that no browser fully implements HTML5. This example needs to be run on a browser that supports HTML5, such as Firefox 3.5 or above.
The main method to implement the File API is very simple, as below: