简体   繁体   中英

How to trigger a file download when clicking an html <a> tag or javascript in a modern browser

I would like to have an a tag (anchor) that triggers a download when clicked.

I've already tried all the solutions in this S/O question and more: How to trigger a file download when clicking an html button or javascript and non works, except for this one:

<a href="lorem.gif" download="lorem.gif">HTML 5 Download</a>

This one works in the latest versions of Firefox and Chrome for certain file types, like images, but doesn't work for PDFs and it doesn't work on IE and many other browsers either.

You are looking for the Content-Disposition HTTP header. You set it on the server-side when you are sending down the file:

Content-Disposition: attachment; filename=lorem.pdf;

It basically tells the browsers that they should download the file instead of trying to render it. See this SO question or this Wikipedia page: MIME#Content-Disposition .

赫雷是如何下载文件

 <a href="lorem.gif" download="lorem.gif"><button>Download</button></a> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM