How Gmail’s Drag and Drop of Attachment From Desktop Works

Recently Gmail pushed out an update that allowed users to drag and drop files from desktop to Gmail and have them automatically uploaded. Being the web geek I am I had to figure out how it functioned. Firefox was easy and I have covered drag and drop uploading already. They also mentioned in their post that Chrome was supported but I know Chrome is yet to implement the File API. Most intriguing was that it doesn’t work in Safari?

The CSS Ninja details how Gmail's drag and drop from the desktop works; when you drag a file from the desktop into Gmail the file will automatically start uploading.

The CSS Ninja recreated the code in a demo (source code [zip]).

The code works in Firefox and Chrome. On Firefox the File API is used (detailed in another blog post) while on Chrome a different API is used.

Plain Text

<div id="drop"> <h1>Drop files here</h1> To add them as attachments <input id="filesUpload" type="file" /></div>    
#drop { position: relative; } #drop input { position: absolute; width: 100%; height: 100%; top: 0; left: 0; opacity: 0; }
 
dropArea.addEventListener("change", TCNDDU.handleDrop, false); TCNDDU.handleDrop = function (evt) { var files = evt.target.files; dropArea.style.display = "none"; for(var i = 0, len = files.length; i &lt;len; i++) { // iterate over file(s) and process them for uploading } };