HTML and CSS Reference
In-Depth Information
else {
alert("Only image files are allowed. Other files will be ignored!");
$("a").hover(ShowPreview, HidePreview);
ShowFileDetails() first empties the table by removing all its rows using the jQuery empty() method. It
then iterates through the FileList and accesses each File object to get the file details. Because the
application is intended only for image files, every file's extension is checked. If a file is an image file ( .jpg ,
.jpeg , .png , or .gif ) then a new row is added to the table. This checking is done with the help of the File
object's type property, which returns the MIME type of a file ( image/jpeg , image/png , and so on). The name
property returns the name of the file with extension but doesn't include the path information. The size
property returns the size of the file in bytes.
You can access individual File objects either using typical collection syntax ( (files[i]) ) or using the
item() method of the FileList object. The Show hyperlink stores an index of the file using a custom data-*
attribute data-ile-index . This way, you can determine which image to show.
The actual image preview is shown when you hover the mouse over the Show link. The jQuery hover()
method binds two handler functions to the hyperlink elements that are invoked when the mouse pointer
enters and leaves the hyperlinks. The ShowPreview() and HidePreview() functions are shown in Listing
Listing 9-21. Showing an Image Preview
function ShowPreview(evt) {
var reader = new FileReader();
$(reader).bind("load",function (e) {
var imgSrc =;
var fileIndex = $('data-file-index');
function HidePreview(evt) {
$("#imgPreview").attr('src', '');
The ShowPreview() function creates an instance of a FileReader . The FileReader object reads files in
asynchronous fashion and raises a load event when a file is successfully read. That is why the event
handler for the load event needs to be attached before reading the file. A file is read using the
readAsDataURL() method of the FileReader object. readAsDataURL() makes the file content available to the
load event handler in the form of a data URL (Base64 encoded). This content can be accessed using the
result property of the object. The load event handler retrieves the file content using the result
property of the FileReader object and then sets the image's src attribute to the image content.
The HidePreview() method simply removes the image's src attribute.
Search WWH ::

Custom Search