The use of the FileReader of HTML5
HTML5 defines FileReader as an important member of the file API for reading files, and the FileReader interface provides a way to read the file and an event model that contains the read result, according to the definition of the system.
FileReader is very simple to use, you can create a FileReader object and invoke its methods as follows:
1. Detection of browser support for FileReader
if (window. FileReader) { var fr = new FileReader (); Add your code here } else { alert (' Not supported by your browser! '); }
2. Methods for invoking FileReader objects
The FileReader instance has 4 methods, 3 of which are used to read the file and the other to interrupt the read. The following table lists these methods, along with their parameters and capabilities, and it is important to note that the method does not return read results regardless of the success or failure of the read , which is stored in the result property.
Eadastext: The method has two parameters, where the second parameter is the encoding of the text, and the default value is UTF-8. This method is very easy to understand, the file is read in text mode, the result of reading is the content of this text file.
readasbinarystring: This method reads a file as a binary string, usually we pass it to the back end, and the backend can store the file through this string.
Readasdataurl: This is the method used in the example program, which reads a file as a string beginning with data: The essence of this string is that the data Url,data URL is a scheme to embed small files directly into the document. Small files here usually refer to files in the format of images and HTML.
The following shows the use of FileReader with an upload image preview and a progress bar upload.
<script type= "Text/javascript" > function Showpreview (source) { var file = source.files[0]; if (window. FileReader) { var fr = new FileReader (); Fr.onloadend = function (e) { document.getElementById ("Portrait"). src = e.target.result; }; Fr.readasdataurl (file); } } </script> <input type= "file" name= "file" onchange= "Showpreview (This)"/>
if (!/image\/\w+/.test (File.type)) { alert ("Make sure the file is an image type"); return false; }
HTML5 file pre-upload local preview