Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drag and drop file attachment into the browser?

It seems Gmail is just starting this feature, and it doesn't require you to install any plugin etc.

It works in both Firefox and Chrome but not IE.

like image 918
Blankman Avatar asked Apr 20 '10 18:04

Blankman


2 Answers

Use dropzonejs.

It's a lightweight library supporting file drops by simply adding the dropzone class to form elements. It handles the files with HTML5 and even shows previews of images dropped into it. In incompatible browsers it falls back to a simple file upload form. Also: it looks good.

Have a look at it!

Disclaimer: I wrote this library.

like image 165
enyo Avatar answered Sep 22 '22 23:09

enyo


Let's summarize one example here before all those links break =)

When you drag and drop with the HTML5 DnD API, a file form your desktop / file browser into the browser:

  • the drop event callback object has a dataTransfer.files property
  • which is a HTML5 File API FileList object
  • which contains File API File objects.

From there on, use the File API to do the upload, which has already been covered in many other places.

Full example:

<div id="file-drop" style="border:1px dashed black; height:300px; width:300px;">Drop files here!</div>
<script>
  var file_drop = document.getElementById('file-drop');
  file_drop.addEventListener(
    'dragover',
    function handleDragOver(evt) {
      evt.stopPropagation()
      evt.preventDefault()
      evt.dataTransfer.dropEffect = 'copy'
    },
    false
  )
  file_drop.addEventListener(
    'drop',
    function(evt) {
      evt.stopPropagation()
      evt.preventDefault()
      var files = evt.dataTransfer.files  // FileList object.
      var file = files[0]                 // File     object.
      alert(file.name)
    },
    false
  )
</script>

Fiddle.

This will alert the file basename (path cannot be obtained from the file API).

BTW, the other basic way you can get File object is through the .files IDL attribute of an input type=file. This method is more friendly for small screens than DnD, where you need two windows open at the same time at good relative positions. Unfortunately, it seems that currently it is not portable to drag and drop into a input type=file: drag drop files into standard html file input

Source: http://www.html5rocks.com/en/tutorials/file/dndfiles/