HTML and CSS Reference
In-Depth Information
function upload_file(file) {
var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.fileName);
xhr.setRequestHeader("X-File-Size", file.fileSize);
xhr.setRequestHeader("X-File-Type", file.type);"GET", "image_upload.php");
function read_image_file(file) {
var reader = new FileReader();
reader.onload = function(e){
var image_contents =;
var img = document.createElement("img");
img.src = image_contents;
Notice that you now have access to the file's name, size, and type, so you send that
data along to the server with the file's contents. Other than that, we're not doing much
extra here that's particularly HTML5y—we're just using standard XHR to upload the
HTML5 gives us the FileReader API, so we can read the contents of a user's local file
and use those contents in our web pages.
The example above shows how to use the contents of an image file to display a preview,
and how to send (i.e., upload) those file contents to a server using Ajax. Of course,
there are a variety of other things you might want to do with the file's contents. For
instance, the FileReader API provides a readAsBinaryString(...) method that gives
you a binary string representation of the file's contents. If you know the format of the
file you are reading, you can perform various operations on this data.
As another example, if you put the image data into an img element (as shown above),
you could use what you learned in Recipe 9.5 , to render that image to a canvas element,
where you can then perform various color and geometric transformations (see Recipes
9.6 and 9.7 ).
At this time, access to local files is restricted to read-only, and it must be initiated by a
user action, such as dragging a file onto the web page or selecting one or more files
from the <input type="file"> element. This is probably for the best, safety-wise, as
allowing pages to write to the local filesystem, while cool, could be quite dangerous!
Search WWH ::

Custom Search