Introduction
In HTML5 we have to communicate with local files by the use of the file API. The File API can be used to create a concise viewing of images, it helps with sending to the server. It provides access by an application to save a file with reference but the user is offline.
Here we have to use the client-side logic to verify and upload a file that matches its file extension or restricts the size of an upload.
The are several interfaces for accessing the local filesystem.
- File: An individual file; provides read-only information such as name, file size, mimetype, and a reference to the filehandle.
- Filelist: An array-like sequence of Fileobjects. (Think <input type="file" multiple> or dragging a directory of files from the desktop).
- Blob: Allows for slicing a file into byte ranges.
The file reader interface can be used to asynchronously read a file through the familiar JavaScript event handling. It is possible to monitor the progress of a read, catch errors, and determine when a load is complete.
Selecting files
- // Check for the various File API support.
- if (window.File && window.FileReader && window.FileList && window.Blob) {
- // Great success! All the File APIs are supported.
- } else {
- alert('The File APIs are not fully supported in this browser.');
- }
Using form input for selecting
The most straightforward way to load a file is to use a standard <input type="file"> element. JavaScript returns the list of selected File objects as a filelist.
- <input type="file" id="files" name="files[]" multiple />
- <output id="list"></output>
- <script>
- function handleFileSelect(evt) {
- var files = evt.target.files; // FileList object
- // files is a FileList of File objects. List some properties.
- var output = [];
- for (var i = 0, f; f = files[i]; i++) {
- output.push('
- <li>
- <strong>', f.name, '</strong> (', f.type || 'n/a', ') - ',
- f.size, ' bytes, last modified: ',
- f.lastModifiedDate.toLocaleDateString(), '
- </li>');
- }
- document.getElementById('list').innerHTML = '
- <ul>' + output.join('') + '</ul>';
- }
- document.getElementById('files').addEventListener('change', handleFileSelect, false);
- </script>
Reading files
After getting a file reference, instantiate a filereader object to read its contents into memory. When the load finishes, the reader is onload event is fired and its result attribute can be used to access the file data.
FileReader includes four options for reading a file.
- FileReader.readAsBinaryString(Blob|File) - In this property will contain the file/blob's data as a binary string.
- FileReader.readAsText(Blob|File, opt_encoding) - Thisproperty will contain the file/blob's data as a text string.
- FileReader.readAsDataURL(Blob|File) - The result property will contain the file/blob's data encoded as a data url.
- FileReader.readAsArrayBuffer(Blob|File) -The result property will contain the file/blob's data as arraybuffer object.
Example: The given example filters out images from the user's selection, call reader.readAsDATAURL() on the file, and renders a thumbnail by setting the src attribute to a data URL.
Code:
- <style>
- .thumb {
- height: 75px;
- border: 1px solid #000;
- margin: 10px 5px 0 0;
- }
- </style>
- <input type="file" id="files" name="files[]" multiple />
- <output id="list"></output>
- <script>
- function handleFileSelect(evt) {
- var files = evt.target.files; // FileList object
- // Loop through the FileList and render image files as thumbnails.
- for (var i = 0, f; f = files[i]; i++) {
- // Only process image files.
- if (!f.type.match('image.*')) {
- continue;
- }
- var reader = new FileReader();
- // Closure to capture the file information.
- reader.onload = (function (theFile) {
- return function (e) {
- // Render thumbnail.
- var span = document.createElement('span');
- span.innerHTML = ['
- <img class="thumb" src="', e.target.result,
- '" title="', theFile.name, '"/>'].join('');
- document.getElementById('list').insertBefore(span, null);
- };
- })(f);
- // Read in the image file as a data URL.
- reader.readAsDataURL(f);
- }
- }
- document.getElementById('files').addEventListener('change', handleFileSelect, false);
- </script>
In this example, we have to read a directory of images.
Slicing a file
In some cases reading the entire file into memory is not the best option.
For example
We wanted to write an async file uploader. One way to speed up the upload would be to read and send the file in separate byte-range chunks. The server component would then be responsible for reconstructing the file content in the correct order.
Code
- if (file.webkitSlice)
- {
- var blob = file.webkitSlice(startingByte, endindByte);
- } else if (file.mozSlice)
- {
- var blob = file.mozSlice(startingByte, endindByte);
- }
- reader.readAsBinaryString(blob);
ForExample
The following example, that reads chunks of a file, uses the onloadend and checks the evt.target.readyState instead of using the onload event.
Code


Join the conversation! Your thoughts help the community grow.