开发者

Force download through js or query

开发者 https://www.devze.com 2023-02-15 06:46 出处:网络
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 t开发者_如何学Co choose eith \"save as\" o

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 t开发者_如何学Co choose eith "save as" or open with ???


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


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


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.


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消