使用 JavaScript/jQuery 下载文件 [英] Download File Using JavaScript/jQuery
问题描述
我在此处指定了一个非常相似的要求.
I have a very similar requirement specified here.
当 $('a#someID').click();
但我不能使用 window.href
方法,因为它用您尝试下载的文件替换当前页面内容.
But I cannot use the window.href
method, since it replaces the current page contents with the file you're trying to download.
相反,我想在新窗口/选项卡中打开下载.这怎么可能?
Instead I want to open the download in new window/tab. How is this possible?
推荐答案
使用不可见的 :
<iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
document.getElementById('my_iframe').src = url;
};
</script>
要强制浏览器下载原本可以渲染的文件(例如 HTML 或文本文件),您需要服务器设置文件的 MIME 类型 为无意义的值,例如 application/x-please-download-me
或 application/octet-stream
,用于任意二进制数据.
To force the browser to download a file it would otherwise be capable of rendering (such as HTML or text files), you need the server to set the file's MIME Type to a nonsensical value, such as application/x-please-download-me
or alternatively application/octet-stream
, which is used for arbitrary binary data.
如果您只想在新选项卡中打开它,唯一的方法是让用户点击一个链接,其 target
属性设置为 _blank代码>.
If you only want to open it in a new tab, the only way to do this is for the user to a click on a link with its target
attribute set to _blank
.
在 jQuery 中:
$('a#someID').attr({target: '_blank',
href : 'http://localhost/directory/file.pdf'});
无论何时单击该链接,它都会在新选项卡/窗口中下载文件.
Whenever that link is clicked, it will download the file in a new tab/window.
这篇关于使用 JavaScript/jQuery 下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!