Home arrow HTML arrow Page 2 - Drag and Drop in HTML5: Parsing Local Files
HTML

Drag and Drop in HTML5: Parsing Local Files


In this second part of a two-part tutorial on the Drag & Drop API in HTML5, we'll be extending the capabilities of the JavaScript application we developed in the first part. After we're done with it in this part, the application will be able to read the contents of dragged-and-dropped files and handle them in a number of interesting ways.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 5
October 11, 2011
TABLE OF CONTENTS:
  1. · Drag and Drop in HTML5: Parsing Local Files
  2. · The File API in action

print this article
SEARCH DEVARTICLES

Drag and Drop in HTML5: Parsing Local Files - The File API in action
(Page 2 of 2 )

While the process may sound intimidating at first, the truth is that reading the contents of dropped files is much easier than one might think. As I explained at the beginning, this can accomplished through the HTML5 File API, whose workhorse is a brand new JavaScript object called “FileReader.”

But I’m getting ahead of myself. The best way to understand how to use the object is with concrete code. Below I defined a couple of JavaScript functions. The first one attaches the familiar “dragover” and “drop” event handlers to the droppable web page area, while the second one reads the contents of the dropped files, as long as they’re images.

Here they are:

// attach the event handlers and handle the dropped files
function initialize() {
    // get the file container
    var filecont = document.getElementById('file-container');
    if (filecont === null) {
        return false;
    }   
   
    // attach the 'dragover' event to the file container
    filecont.addEventListener('dragover', function(event) {
        event.preventDefault();
    }, true);
   
    // attach the 'drop' event to the file container
    filecont.addEventListener('drop', function(event) {
        event.preventDefault();
        var files = event.dataTransfer.files;
        for(var i = 0; i < files.length; i++) {
            readFile(files[i], event.target)
        }
    }, true); 
}

// read the dropped files (only images are accepted)
function readFile(file, element) {
    if (!file.type.match(/image.*/)) {
        return false;
    }
   
    // create the file reader
    var reader = new FileReader();
    // display the image in the target container
    reader.onload = function(event) {
        var img = document.createElement('img');
        img.setAttribute('src', reader.result);
        element.appendChild(img);
    }
    // read the image's contents
    reader.readAsDataURL(file);
}

// call the 'initialize()' function after the web page has been loaded
window.addEventListener('load', initialize, true);

Certainly, the logic that stands behind the “initialize()” function should be quite familiar to you. It defined a similar function in the preceding part of this tutorial. In either case, all it does is attach the previously mentioned event handlers to the target area on the web page and pass the lists of dropped files to its counterpart “readFile().”

And here’s where things become really interesting. As you can see, this function first checks that the inputted file is actually an image (of course, you can change this and accept other file types as well). Then, it uses the file reader’s “readAsDataURL()” method to read the file’s contents, which are finally assigned to the “src” attribute of an <img> element created on the fly and appended dynamically to the DOM.

Furthermore, if you’re wondering how the pertinent file contents are dropped into the <img> element, the following lines will make things much clearer:

reader.onload = function(event) {
        var img = document.createElement('img');
        img.setAttribute('src', reader.result);
        element.appendChild(img);
    }

Effectively, the “onload” event is called after the target file has been read, regardless of the success or failure of operation, and the corresponding contents are stored in the “result” property. The rest of the snippet is plain DOM manipulation, so feel free to skip over it if you want to.

So far, so good. At this point, I've managed to create a basic JavaScript snippet, which allows users to drag local images and drop them into a web page container, where they’re displayed accordingly. So, what's next? Well, naturally the snippet must be attached to the earlier web page, so these two tiers can work side by side in sweet harmony.

This will be done in the next segment, so keep reading. 

Attaching the earlier JavaScript snippet to the sample web page

If you want to test the earlier drag & drop script to see if it works as expected, below I listed for you its full source code. Check it out:

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HTML 5 File API</title>
<script>
// attach the event handlers and handle the dropped files
function initialize() {
    // get the file container
    var filecont = document.getElementById('file-container');
    if (filecont === null) {
        return false;
    }   
   
    // attach the 'dragover' event to the file container
    filecont.addEventListener('dragover', function(event) {
        event.preventDefault();
    }, true);
   
    // attach the 'drop' event to the file container
    filecont.addEventListener('drop', function(event) {
        event.preventDefault();
        var files = event.dataTransfer.files;
        for(var i = 0; i < files.length; i++) {
            readFile(files[i], event.target)
        }
    }, true); 
}

// read the dropped files (only images are accepted)
function readFile(file, element) {
    if (!file.type.match(/image.*/)) {
        return false;
    }
   
    // create the file reader
    var reader = new FileReader();
    // display the image in the target container
    reader.onload = function(event) {
        var img = document.createElement('img');
        img.setAttribute('src', reader.result);
        element.appendChild(img);
    }
    // read the image's contents
    reader.readAsDataURL(file);
}

// call the 'initialize()' function after the web page has been loaded
window.addEventListener('load', initialize, true);
</script>
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #fff;
    font: normal 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
h1 {
    font-size: 5em;
    color: #585858; 
}
h2 {
    font-size: 3em;
    text-align: center;
    color: #585858;
}
/* main wrapper */
#wrapper {
    width: 780px;
    margin: 0 auto;
}
/* file container */
#file-container {
    width: 700px;
    min-height: 500px;
    margin: 0 auto;
    background: #eee;
    border: 3px dotted #585858;
}
</style>
</head>
<body>
    <div id="wrapper">
        <header>
            <h1>HTML 5 File API</h1>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        </header>
        <section>
            <h2>Drop your images below...</h2>
            <div id="file-container"></div>
        </section>
        <footer>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet.</p>
        </footer>
    </div>
</body>
</html>

Mission accomplished. Now, all that you have to do is to fire up Firefox and open a local folder containing some images. Done? Good. Now, drag and drop a few of them onto the corresponding web page container (yes, you can select multiple files also). If all went well, the droppable area should look similar to the one depicted in the following screen capture:

That looks pretty good, doesn’t it? Not only does HTML5 make it possible to drag and drop local files into a section on a web page, but the implementation of a script that exploits this functionality is pretty straightforward. So start tweaking the previous script to fit your own needs. It’ll be a fun and instructive experience, trust me.

Closing remarks

In this two-part tutorial, I provided you with a quick introduction to using the Drag & Drop and File APIs included with HTML5. As you just saw, putting the APIs to work is in general quite easy, even though handling certain events and reading the contents of the target files isn’t as intuitive as one might expect.

Needless to say, the major drawback in this case is the lack of solid support by most modern browsers. Hopefully, that will change in the reasonably near future. As usual, only time will tell.

See you in the next web design tutorial!  


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
HTML ARTICLES

- Does HTML5 Need a Main Element?
- Revisiting the HTML5 vs. Native Debate
- HTML5: Not for Phone Apps?
- HTML5 or Native?
- Job Hunting? Freelancer.com Lists This Quart...
- HTML5 in the News
- Report: HTML5 Mobile Performance Lags
- The Top HTML5 Audio Players
- Top HTML5 Video Tutorials
- HTML5: Reasons to Learn and Use It
- More of the Top Tutorials for HTML5 Forms
- MobileAppWizard Releases HTML5 App Builder
- HTML5 Boilerplate: Working with jQuery and M...
- HTML5 Boilerplate Introduction
- New API Platform for HTML5

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials