Working with Local Files
At last HTML provides a standard way to interact with the user’s local files, using HTML5’s File API specification. There are several ways to access external files:
File
provides information including name, size, and MIME type, and gives a reference to the file handle.FileList
is an array-like sequence of File objects.- The
FileReader
interface uses File and FileList to asynchronously read a file. You can check on read progress, catch any errors, and find out when a file is completely loaded.
Checking for Browser Support
Once more, you can check whether your browser supports the File API by the usual feature-detection method:
if (window.File && window.FileReader && window.FileList) { // we're good }
Try it Yourself: Interacting with the Local File System
In this example you’re going to modify the previous drag-and-drop example to allow a list of files to be dragged into a web page from the local file system. To do so, you’re going to use the FileList data structure
Take a look at the modified drop(ev) function:
function drop(ev) { var files = ev.dataTransfer.files; for (var i = 0; i < files.length; i++) { var f = files[i]; var pnode = document.createElement("p"); var tnode = document.createTextNode(f.name + " (" + f.type + ") " + f.size + " bytes"); pnode.appendChild(tnode); ev.target.appendChild(pnode); } ev.preventDefault(); }
Here, the array-like FileList containing information about the dragged files is extracted from the dataTransfer object:
var files = ev.dataTransfer.files;
Then, each file is processed in turn by iterating through them individually:
for (var i = 0; i < files.length; i++) { var f = files[i]; ...statements to process each file ... }
The complete code here:
<!DOCTYPE HTML> <html> <head> <title>HTML5 Local Files</title> <style> body {background-color: #ddd; font-family: arial, verdana, sansserif;} #drop1 { width: 400px; height: 200px; border: 1px solid black; background-color: white; padding: 10px; } </style> <script> function allowDrop(ev) { ev.preventDefault(); } function drop(ev) { var files = ev.dataTransfer.files; for (var i = 0; i < files.length; i++) { var f = files[i] var pnode = document.createElement("p"); var tnode = document.createTextNode(f.name + " (" + f.type + ") " + f.size + " bytes"); pnode.appendChild(tnode); ev.target.appendChild(pnode); } ev.preventDefault(); } window.onload = function() { var drophere = document.getElementById("drop1"); drophere.ondragover = allowDrop; drophere.ondrop = drop; } </script> </head> <body> <div id="drop1" ></div> </body> </html>
After creating this file in your editor and loading the resulting page into the browser, you should be able to drag files into the drop area from your local system, and see filename, MIME type, and size show like below snapshot.