Force download through js or query

2019-01-02 21:11发布

Is it possible to force a download through JS or Javascript i-e the web page should not open the file in new tab in the browser but to pop up to let the user to choose eith "save as" or open with ???

5条回答
路过你的时光
2楼-- · 2019-01-02 21:36

You can not force that behavior from JavaScript, the HTTP Headers need to be set on the server side:

Content-disposition=attachment; filename=some.file.name

The way you can solve the problem is to let your AJAX method redirect the user to the URL of the PDF:

location.replace('path/to.pdf');

(The above HTTP headers must be set for the PDF)


Update

At the time of this answer, it wasn't possible. Now it is, scroll down to see the other answer saying so.

查看更多
临风纵饮
3楼-- · 2019-01-02 21:38

dynamic create link and click it with download attribute for force download as file:

var anchor = document.createElement('a');
anchor.href = this.props.download_url;
anchor.target = '_blank';
anchor.download = this.props.file_name;
anchor.click();

Take a notice that i didn't even added it to DOM, so it's fast.

P.S download attribute won't work with IE. But it will just open link in new tab. http://caniuse.com/#feat=download

查看更多
何处买醉
4楼-- · 2019-01-02 21:50

No, it is not possible and thanks God it isn't. Otherwise I leave you to the imagination of what kind of files could be stored on your computer when you visit a web site without you knowing it.

As @Paul D. White pointed out in the comments section if you want to open the file inline (inside the browser) with the default program associated with it you could have the server send the Content-Disposition HTTP header. For example:

Content-Disposition: inline; filename=foo.pdf
查看更多
浪荡孟婆
5楼-- · 2019-01-02 21:56

With the advent of HTML5 you could just use the new property download in the anchor tag.

The code will look something like

<a download="name_of_downloaded_file" href="path/to/the/download/file"> Clicking on this link will force download the file</a>

It works on firefox and chrome latest version. Should I mention that I didn't check it in IE? :P

Edited the download attribute after comment from sstur


https://caniuse.com/#feat=download

查看更多
柔情千种
6楼-- · 2019-01-02 21:58

No this is not possible with JQuery/JavaScript only.

You will need a server side script which returns you the file with a Content-Type (HTTP Header) which will force the browser to download your requested file. An possible value for Content-Type would be application/force-download.

查看更多
登录 后发表回答