HTML and CSS Reference
In-Depth Information
10.7 Local Files
Problem
You want users to be able to read an image file from their local filesystem and do
something with it in the web page, such as previewing or uploading it.
Solution
Prior to HTML5, the only interaction users could have with their local filesystem was
through the <input type="file"> element. This functionality was opaque as far as the
page's JavaScript was concerned, because the page couldn't see anything about the file
selected, or interact with it in any meaningful way.
HTML5 gives us the FileReader API, which lets us take a reference to a local file and
read its contents directly into the web page. To test if the browser supports the enhanced
FileReader API, use the following feature-detect:
var history_support = typeof FileReader != "undefined";
We saw in Recipe 10.3 , how to get a reference to a local file or files using the native
drag-and-drop functionality. In a very similar way, we can now get a reference to the
local file(s) selected by the user in an <input type="file"> element:
<p>Pick an image file:</p>
<input type="file" id="file_selector" />
<script>
var file_selector = document.getElementById("file_selector");
file_selector.addEventListener("change", function(){
var files_array = this. files ;
// Now you have a reference to the file(s) that the user selected.
// Do something cool with them!
}, false);
</script>
Either way, once you have a reference to a local file, such as an image file, you can read
the contents of that file using a FileReader instance:
function read_image_file(file) {
var reader = new FileReader() ;
reader.onload = function(e){
var image_contents = e. target.result ;
// now you have the contents of the file
};
reader. readAsDataURL (file);
}
Now that you have the file contents—in this case, as a data URI (base64 encoding of
the file)—you can display the contents in an img element. The code all put together
looks like this:
 
Search WWH ::




Custom Search