Is it possible to drag+drop a file from the browser to the desktop, causing a download?
I have an app that stores files and uses开发者_运维技巧 drag+drop to upload them. Is there a way I can drag+drop to download the file to my desktop instead of having to click "download." Basically, the opposite of drag+drop upload.
The html5rocks and cssninja are ok, but I think way overkill for quick answers. Here is a simple example of using drag events from something, including to download files.
<style>
div { background-color: #eee; border: 1px solid black; padding: 5px; float: left; clear: both; }
</style>
<div id="uiLinkText" draggable="true">Drag <b>Text</b> to a text editor </div>
<div id="uiLinkHyperlink" draggable="true">Drag <b>Hyperlink</b> to address bar </div>
<div id="uiLinkUrlDownload" draggable="true">Drag <b>Url Download</b> to file system </div>
<div id="uiLinkStaticDownload" draggable="true">Drag <b>Static Download</b> to file system </div>
<script>
document.getElementById('uiLinkText').ondragstart = function(event){
// plain text, for dropping into text editor
event.dataTransfer.setData('text/plain', 'Go to http://stackoverflow.com/questions/5411481/ to read about this.');
}
document.getElementById('uiLinkHyperlink').ondragstart = function(event){
// URL, for dropping into the browser's address bar
event.dataTransfer.setData('text/uri-list', 'http://stackoverflow.com/questions/5411481/');
}
document.getElementById('uiLinkUrlDownload').ondragstart = function(event){
// file download contents, for dropping into a file system
event.dataTransfer.setData('DownloadURL', 'text/plain:SourceQuestion.html:http://stackoverflow.com/questions/5411481/')
}
document.getElementById('uiLinkStaticDownload').ondragstart = function(event){
var textToWrite = 'file contents here';
var textFileAsBlob = new Blob([textToWrite], { type: 'text/xml' });
var url = window.URL.createObjectURL(textFileAsBlob);
// file download contents, for dropping into a file system
event.dataTransfer.setData('DownloadURL', 'text/plain:Static.txt:' + url)
}
</script>
Warning: While this worked fine for me in Chrome locally (in Windows 7), when I tried putting it on jsfiddle for a linke, the "Static Download" did not work, and the "Url Download" crashed Google Chrome.
As with most drag-and-drop, it does not work with MSIE 9, I have not tried 10+ or Firefox.
It is supported in Google Chrome only.
http://www.html5rocks.com/en/tutorials/dnd/basics/#toc-desktop-dnd-out
For example it is implemented in Gmail.
None of any other browsers support this behavior.
No, you would need to be able to set a download path, if nothing else, which no browsers allow you to do. It's possible with a plugin, but not straight JS.
精彩评论