PDF file not downloading with HTML5 download attribute

大兔子大兔子 提交于 2019-12-01 12:42:11

Download Basics

So essentially what is happening is that when you link to a file URL, the browser opens that URL and if it has accessibility to display the content, it almost always will. Some most common examples of this are image files (.png, .jpg, etc...). However, if the browser can't read the file type (.zip) then it will almost always download the content. A great way to force the browser to download the file is by adding the download attribute in the <a> tag.

PDFs are readable and accessible by most modern browsers so by default, the browser is set to open the file instead of download it. Because of this accessibility, most modern browsers have introduced settings that allow users to decide on a machine by machine basis whether or not a PDF (or any other readable file) should open in another window or download by default. In many cases, even with the download attribute, the browser can still decide for itself how to handle the file.

Possible Solutions

1 - If you are just trying to achieve the download functionality on your browser only (which it looks like you aren't but I thought I should include anyway), you can open chrome, go to Settings -> Advanced Settings -> Content Settings -> PDF Documents -> Toggle on Download

2 - You can compress and zip the file so the browser is forced to download the file.

3 - If you have root server access to your site and it is using Apache, you can add the following to your .htaccess

ForceType application/octet-stream
Header set Content-Disposition attachment

If you are using an NGINX web server, you can add the following redirect

location ~* (.*\.pdf) {
types { application/octet-stream .pdf; }
default_type application/octet-stream;
}

you cannot use <a download href="files/pdf-sample.pdf"> but you can use <a href="files/pdf-sample.pdf"> for preview your file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!