twitter@js_bankfacebook@jsbankrss@jsbank






Processing Local Files in JavaScript with HTML5 In previous JavaScript articles and JavaScript code examples, jsB@nk provided you many posts about new HOT features/functions in HTML5, such as:

- JavaScript Caching in HTML5
- Awesome Canvas Drawer with HTML5
- JavaScript in HTML5 vs ActionScript 3 in Flash in Drawing Match - Who Win?
- HOT New JavaScript APIs with HTML5

Today in this post, jsB@nk is happy to give you one more JavaScript article tutorial for another new HOT feature in HTML5 - local files processing. Throughout this JavaScript article tutorial, you're able to handle how to create, delete, read, write and query the local files with JavaScript on HTML5. Please go to the inner page for full detailed instructions, guides and live demos of JavaScript HTML5 code examples for HTML5 file uploading, uploading file JavaScript, JavaScript open file, JavaScript file read, JavaScript load file, javascript create file.


Generate your business videos by AI with voice or just text



Your first FREE AI Video App! Automate Your First AI Video. Create Your Professional Video In 5 Minutes By AI No Equipment Or Video Editing Skill Requred. Effortless Video Production For Content Marketers.
Free UNLMITED AI Video App in Your Hand

HTML5 finally provides a standard way to interact with local files, via the File API specification. As example of its capabilities, the File API could be used to create a thumbnail preview of images as they're being sent to the server, or allow an app to save a file reference while the user is offline. Additionally, you could use client-side logic to verify an upload's mimetype matches its file extension or restrict the size of an upload.

The spec provides several interfaces for accessing files from a 'local' filesystem:

  1. File - an individual file; provides readonly information such as name, file size, mimetype, and a reference to the file handle.
  2. FileList - an array-like sequence of File objects. (Think <input type="file" multiple> or dragging a directory of files from the desktop).
  3. Blob - Allows for slicing a file into byte ranges.

When used in conjunction with the above data structures, the interface can be used to asynchronously read a file through familiar JavaScript event handling. Thus, it is possible to monitor the progress of a read, catch errors, and determine when a load is complete. In many ways the APIs resemble XMLHttpRequest's event model.

Note: At the time of writing this tutorial, the necessary APIs for working with local files are supported in Chrome 6.0 and Firefox 3.6. As of Firefox 3.6.3, the File.slice() method is not supported.

Selecting files

The first thing to do is check that your browser fully supports the File API:

// 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.');
}

Of course, if you're app will only use a few of these APIs, modify this snippet accordingly.

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. Here's an example that uses the 'multiple' attribute to allow selecting several files at once:

<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</li>');
   
}
    document
.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
 
}

  document
.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

Example: Using form input for selecting. Try it!

Using drag and drop for selecting

Another technique for loading files is native drag and drop from the desktop to the browser. We can modify the previous example slightly to include drag and drop support.

<div id="drop_zone">Drop files here</div>
<output id="list"></output>

<script>
 
function handleFileSelect(evt) {
    evt
.stopPropagation();
    evt
.preventDefault();

   
var files = evt.dataTransfer.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</li>');
   
}
    document
.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
 
}

 
function handleDragOver(evt) {
    evt
.stopPropagation();
    evt
.preventDefault();
 
}

 
// Setup the dnd listeners.
 
var dropZone = document.getElementById('drop_zone');
  dropZone
.addEventListener('dragover', handleDragOver, false);
  dropZone
.addEventListener('drop', handleFileSelect, false);
</script>

Example: Using drag and drop for selecting. Try it!

Drop files here

Note: Some browsers treat <input type="file"> elements as native drop targets. Try dragging files onto the input field in the previous example.


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web