Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

javascript - 使用Javascript / jQuery下载文件(Download File Using Javascript/jQuery)

I have a very similar requirement specified here .

(我在这里指定了非常相似的要求。)

I need to have the user's browser start a download manually when $('a#someID').click();

(我需要让用户的浏览器在$('a#someID').click();时手动开始下载$('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.

(但我无法使用window.href方法,因为它将当前页面内容替换为您尝试下载的文件。)

Instead I want to open the download in new window/tab.

(相反,我想在新窗口/选项卡中打开下载。)

How is this possible?

(这怎么可能?)

  ask by Mithun Sreedharan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use an invisible <iframe> :

(使用不可见的<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.

(要强制浏览器下载文件,否则它将能够呈现(例如HTML或文本文件),您需要服务器将文件的MIME类型设置为无意义的值,例如application/x-please-download-me或者application/octet-stream ,用于任意二进制数据。)

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 .

(如果您只想在新选项卡中打开它,唯一的方法是让用户单击链接并将其target属性设置为_blank 。)

In jQuery:

(在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.

(只要单击该链接,它就会在新的选项卡/窗口中下载该文件。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...