使用Javascript / jQuery下载文件 [英] Download File Using Javascript/jQuery
问题描述
我的规定与此处有非常相似的要求。
我需要让用户的浏览器在 $('a#someID')时手动下载。click();
但是,我不能使用 window.href
方法,因为它将使用您要下载的文件替换当前页面内容。
相反,我想在新窗口/标签中打开下载。
使用不可见的< iframe>
:
< iframe id =my_iframestyle =display:none;>< / iframe>
< script>
function下载(url){
document.getElementById('my_iframe')。src = url;
};
< / script>
要强制浏览器下载文件,否则将能够呈现(例如HTML或文本文件),您需要服务器将文件的 MIME类型设置为无意义的值,例如 application / x-please-download-me
或者另外 application / octet-stream
,用于任意二进制数据。
如果您只想在新标签页中打开它,唯一的方法是让用户点击链接,其 target
属性设置为 _blank
。
在jQuery中: strong>
$('a#someID')。attr({target:'_blank',
href:的 'http://localhost/directory/file.pdf'});
无论何时点击该链接,它将在新的标签/窗口中下载该文件。 >
I have a very similar requirement specified here.
I need to have the user's browser start a download manually when $('a#someID').click();
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?
Use an invisible <iframe>
:
<iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
document.getElementById('my_iframe').src = url;
};
</script>
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.
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
.
In 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屋!