Drag and Drop is one of the many exciting features of HTML5, supported by mainstream modern browsers, including the latest versions of IE! How great is that!
Recently, Google released a new feature that allows dragging files from the browser to a specified folder, and yes, you heard it correctly, to any folder you want to drag to. Isn’t that exciting for all the geeks out there?!
Originally, it was Brother L who told me about this feature for Gmail attachments, and after trying it, it was indeed amazing that files can be dragged from a webpage into any folder in the operating system to complete the download process.
I researched a lot and finally found a way to achieve this, and I’d like to share everything I know here.
To implement this feature, we currently only need the following things:
I believe these things should not be hard to obtain~
Next, we are ready to get started:
Attribute mapping is often used to test the browser's support for HTML5 API properties. For example, by looking for the draggable attribute to check if elements with [draggable="true"] support the ** Drag and Drop API**:
"draggable" in document.createElement("div");
// As of writing this article, only Chrome supports this feature
/chrome/.test( navigator.userAgent.toLowerCase() );
If all goes well, congratulations, you can now enter the next game phase.
Dragging for download has high requirements for file addresses; it must be in the following format to enable drag-and-drop downloading:
{MiME}:{FileName}:{FileUrl}
For example:
image/jpeg:Penguins.jpg:https://www.box.net/box_download_file?file_id=f66690
Through practice, it has been found that this function can only work if all three parameters are valid.
After completing the above work, the next step is to bind the event.
var url='image/jpeg:Penguins.jpg:https://www.box.net/box_download_file?file_id=f66690';
document.body.addEventListener("dragstart",function(e) {
e.dataTransfer.setData("DownloadURL", url);
});
Well, everything is ready, and now go back to your browser and feel free to drag images, text, or any draggable elements into the folder. Can you see a file named Penguins.jpg calmly lying in the folder you dragged to? Haha, isn’t it amazing?
Alright, the function has been implemented, but I have to go on a bit. Personally, I think this is a great user experience, but it might also turn out to be a redundant feature. 1. Browser compatibility - As of now, only Chrome supports it, but for Google, promoting it to gain traction shouldn’t be an issue. 2. Security - In theory, the files dragged down can come from any domain, and both the file name and file type can be modified with JavaScript. What would happen if someone with malicious intent added a harmful script to the webpage, replacing the drag path, disguising a malicious file as the same name as the one you want to download?
You might want to continue learning about: HTML5 File API for Resuming Downloads