PDF file not downloading with HTML5 download attribute

后端 未结 3 2045
不知归路
不知归路 2020-12-10 20:22

I have a download attribute on two different anchor tags. One is for an Excel file and one for PDF. The Excel file downloads. The PDF opens in new tab instead. Why is this h

相关标签:
3条回答
  • 2020-12-10 20:50

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

    0 讨论(0)
  • 2020-12-10 20:58

    So the solution is:

    <a href="pdf-sample"  download="pdf-samle.pdf">
    

    Note that "href" has a value without the .pdf reduction, but "download" has a value with the .pdf reduction. Remember you also have to remove the .pdf reduction from the targeted file. As it seems the browser treats the downloaded file as a non pdf file and therefore is not opening it by default.

    0 讨论(0)
  • 2020-12-10 21:01

    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;
    }
    
    0 讨论(0)
提交回复
热议问题