Drag’n’drop images example

Drag and drop images with thumbnail previews

This time, let’s reuse the readFilesAndDisplayPreview() method we saw in the File API chapter in the HTML5 Part 1 course.

We have reproduced the example here – please review the source code to refresh your memory (click on the JS tab or look at the example at CodePen).

Click the “Choose files” button (an <input type=”file”> element), select one or more images — and you should see image thumbnails displayed in the open space beneath it:

Source code extract (the part that reads the image file content and displays the thumbnails):

  1. function readFilesAndDisplayPreview(files) {
  2.    // Loop through the FileList and render image files
  3.    // as thumbnails.
  4.    for (var i = 0, f; f = files[i]; i++) {
  5.      // Only process image files.
  6.      if (!f.type.match(‘image.*’)) {
  7.         continue;
  8.      }
  9.      var reader = new FileReader();
  10.      //capture the file information.
  11.      reader.onload = function(e) {
  12.          // Render thumbnail.
  13.          var span = document.createElement(‘span’);
  14.          span.innerHTML = “<img class=’thumb’ src='” +
  15.                            e.target.result + “‘/>”;
  16.          document.getElementById(‘list’).insertBefore(span, null);
  17.      };
  18.      // Read the image file as a data URL. Will trigger
  19.      // a call to the onload callback above
  20.      // only once the image is completely loaded
  21.      reader.readAsDataURL(f);
  22.    }
  23. }

At line7, there is a test that will avoid processing non image files. The “!” is the NOT operator in JavaScript. The call to continue at line 8 will make the for loop go to its end and process the next file. See the HTML5 part 1 course about the file API for more details (each file has a name, type, lastModificationDate and size attribute. The call to match(…) here is a standard way in JavaScript to match a string value with a regular expression).

At line 19, we insert the <img> element that was created and initialized with the dataURL of the image file, into the HTML list with an id of “list”.

So, let’s add this method to our code example, to display file details once dropped, and also add an <output id=”list”></output> to the HTML of this example.

Complete example of drag and drop + thumbnails of images

ilmage drag'n'drop with thumbnails

Try it below in your browser (drag’n’drop image files into the drop zone) or play with it at CodePen:

Complete source code:

  1. <!DOCTYPE html>
  2. <html lang=”en”>
  3. <head>
  4.     <style>
  5.        div {
  6.           height: 150px;
  7.           width: 350px;
  8.           border: 2px solid #666666;
  9.           backgroundcolor: #ccc;
  10.           marginright: 5px;
  11.           borderradius: 10px;
  12.           boxshadow: inset 0 0 3px #000;
  13.           textalign: center;
  14.           cursor: move;
  15.        }
  16.        .dragged {
  17.           border: 2px dashed #000;
  18.           backgroundcolor: green;
  19.        }
  20.        .draggedOver {
  21.           border: 2px dashed #000;
  22.           backgroundcolor: green;
  23.        }
  24.      </style>
  25.      
  26.        function dragLeaveHandler(event) {
  27.           console.log(“drag leave”);
  28.           // Set style of drop zone to default
  29.           event.target.classList.remove(‘draggedOver’);
  30.        }
  31.        function dragEnterHandler(event) {
  32.           console.log(“Drag enter”);
  33.           // Show some visual feedback
  34.           event.target.classList.add(‘draggedOver’);
  35.        }
  36.        function dragOverHandler(event) {
  37.           //console.log(“Drag over a droppable zone”);
  38.           // Do not propagate the event
  39.           event.stopPropagation();
  40.           // Prevent default behavior, in particular when we drop images or links
  41.           event.preventDefault();
  42.        }
  43.        function dropHandler(event) {
  44.           console.log(‘drop event’);
  45.           // Do not propagate the event
  46.           event.stopPropagation();
  47.           // Prevent default behavior, in particular when we drop images or links
  48.           event.preventDefault();
  49.           // reset the visual look of the drop zone to default
  50.           event.target.classList.remove(‘draggedOver’);
  51.           // get the files from the clipboard
  52.           var files = event.dataTransfer.files;
  53.           var filesLen = files.length;
  54.           var filenames = “”;
  55.           // iterate on the files, get details using the file API
  56.           // Display file names in a list.
  57.           for(var i = 0 ; i  filesLen ; i++) {
  58.              filenames += ‘\n’ + files[i].name;
  59.              // Create a li, set its value to a file name, add it to the ol
  60.              var li = document.createElement(‘li’);
  61.              li.textContent = files[i].name;
  62.              document.querySelector(“#droppedFiles”).appendChild(li);
  63.           }
  64.           console.log(files.length + ‘ file(s) have been dropped:\n’ + filenames);
  65.           readFilesAndDisplayPreview(files);
  66.        }
  67.        function readFilesAndDisplayPreview(files) {
  68.           // Loop through the FileList and render image files as thumbnails.
  69.           for (var i = 0, f; f = files[i]; i++) {
  70.           // Only process image files.
  71.           if (!f.type.match(‘image.*’)) {
  72.              continue;
  73.           }
  74.           var reader = new FileReader();
  75.           //capture the file information.
  76.           reader.onload = function(e) {
  77.              // Render thumbnail.
  78.              var span = document.createElement(‘span’);
  79.              span.innerHTML =  + e.target.result + “‘/>”;
  80.              document.getElementById(‘list’).insertBefore(span, null);
  81.           };
  82.           // Read the image file as a data URL. Will trigger the call to the above callback when
  83.           // the image file is completely loaded
  84.           reader.readAsDataURL(f);
  85.        }
  86.     }
  87.   
  88. </head>
  89. <body>
  90. <h2>Drop your files here!</h2>
  91.  id=“droppableZone” ondragenter=dragEnterHandler(event) ondrop=dropHandler(event)
  92.                          ondragover=dragOverHandler(event)   ondragleave=dragLeaveHandler(event)>
  93.     Drop zone
  94.     
       id=“droppedFiles”>
  • <br/>
  • <output id=“list”></output>
  • <body>
  • <html>
  • Above, we added the readFilesAndDisplayPreview() method detailed earlier. We called it at the end of the drop handler (line 77), and we added the <output> element as a container for the <img> elements (constructed by the JavaScript code lines 94-96) which will display the thumbnails (line 114).