是否可以将文件从浏览器拖放到桌面,导致下载?

Mat*_*man 5 javascript php jquery drag-and-drop

我有一个存储文件的应用程序,并使用拖放来上传它们.有没有办法我可以拖放下载文件到我的桌面而不必点击"下载".基本上,与拖放上传相反.

Aba*_*cus 7

html5rocks 和 cssninja 都可以,但我认为快速回答有点过分了。这是一个使用拖动事件的简单示例,包括下载文件。

<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>
Run Code Online (Sandbox Code Playgroud)

警告:虽然这在本地 Chrome 中(在 Windows 7 中)对我来说效果很好,但当我尝试将其放在 jsfiddle 上进行链接时,“静态下载”不起作用,并且“Url 下载”使 Google Chrome 崩溃。

与大多数拖放操作一样,它不适用于 MSIE 9,我还没有尝试过 10+ 或 Firefox。


小智 1

不,您需要能够设置下载路径,如果没有其他的话,没有浏览器允许您这样做。可以通过插件实现,但不能直接使用 JS。

  • 错误——(现在)可以做到这一点。Chrome 有一个方法(见下面的答案),并且 Firefox 似乎需要一个扩展(http://superuser.com/questions/758797/downloading-files-with-drag-and-drop) (2认同)