我在这里指定了一个非常类似的需求。
我需要有用户的浏览器手动启动下载时$('a#someID').click();
但是我不能用窗户。Href方法,因为它将当前页面内容替换为您试图下载的文件。
相反,我想在新窗口/标签中打开下载。这怎么可能呢?
我在这里指定了一个非常类似的需求。
我需要有用户的浏览器手动启动下载时$('a#someID').click();
但是我不能用窗户。Href方法,因为它将当前页面内容替换为您试图下载的文件。
相反,我想在新窗口/标签中打开下载。这怎么可能呢?
当前回答
适用于Chrome, Firefox和IE8及以上。
var link=document.createElement('a');
document.body.appendChild(link);
link.href=url ;
link.click();
其他回答
也可以使用fs-浏览器包。 它有很好的和简单的下载方法为客户端。 它是这样的:
import {downloadFile} from 'fs-browsers'; downloadFile (url-to-the-file);
2019现代浏览器更新
这是我现在推荐的方法,但有几点注意事项:
需要一个相对现代的浏览器 如果文件非常大,您可能会采取与原始方法(iframe和cookie)类似的方法,因为以下一些操作可能会消耗至少与正在下载的文件相同大的系统内存和/或其他有趣的CPU副作用。
fetch('https://jsonplaceholder.typicode.com/todos/1') .then(resp => resp.blob()) .then(blob => { const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; a.href = url; // the filename you want a.download = 'todo-1.json'; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); alert('your file has downloaded!'); // or you know, something with better UX... }) .catch(() => alert('oh no!'));
2012年原创的jQuery/iframe/cookie的方法
我已经创建了jQuery文件下载插件(演示)(GitHub),这也可以帮助您的情况。它的工作原理与iframe非常相似,但有一些很酷的功能,我发现相当方便:
Very easy to setup with nice visuals (jQuery UI Dialog, but not required), everything is tested too User never leaves the same page they initiated a file download from. This feature is becoming crucial for modern web applications successCallback and failCallback functions allow for you to be explicit about what the user sees in either situation In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for an example of this.
下面是一个简单的用例演示,使用带有承诺的插件源代码。演示页面还包括许多其他“更好的用户体验”示例。
$.fileDownload('some/file.pdf')
.done(function () { alert('File download a success!'); })
.fail(function () { alert('File download failed!'); });
使用一个不可见的<iframe>:
<iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
document.getElementById('my_iframe').src = url;
};
</script>
为了迫使浏览器下载它本来能够呈现的文件(例如HTML或文本文件),您需要服务器将文件的MIME Type设置为一个无意义的值,例如application/x-please-download-me或application/octet-stream,这用于任意二进制数据。
如果您只想在一个新选项卡中打开它,唯一的方法是让用户单击目标属性设置为_blank的链接。
jQuery:
$('a#someID').attr({target: '_blank',
href : 'http://localhost/directory/file.pdf'});
无论何时单击该链接,它都会在一个新的选项卡/窗口中下载文件。
如果您不需要浏览另一个页面,这可能会很有帮助。 这是一个基本的javascript函数,所以可以用在任何平台的后端是javascript
window.location.assign('any url or file path')
使用iframe的简单示例
function downloadURL(url) {
var hiddenIFrameID = 'hiddenDownloader',
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = url;
};
然后在任何你想要的地方调用这个函数:
downloadURL(“path / to /我的文件”);