How can I create a download link of a PDF that does not require a right click?

后端 未结 6 1239
清酒与你
清酒与你 2020-12-15 02:01

I am working on a website where the visitor should be able to download a pdf file. (There are three links to choose from but that is irrelevant) I wanted to know how to mak

6条回答
  •  不知归路
    2020-12-15 02:28

    All you basically need to do is to set the Content-Disposition header to attachment to get a 'Save As' dialogue. Here's a kickoff PHP example:

    
    

    You can't and don't want to do this with Javascript.

    Important note: due to a poor feature, in MSIE the default filename in 'Save As' dialogue won't be derived from the content-disposition header, it will instead be the last part of the pathinfo in the request URL. To workaround this, append the PDF filename to the link, e.g. http://example.com/pdf/foo.pdf. You can even make use of it in PHP to read the in the pathinfo specified PDF file. Here's a basic example of pdf.php:

    
    

    This however assumes that you've MultiViews on so that /pdf/ will go through this PHP file, or at least a RewriteRule from /pdf/ to /pdf.php/.

    The major advantage of this approach is that you don't need to change the code whenever you want to add a new PDF file or change the PDF file name.

    You can even make it more generic by automatically determining and setting the correct content type:

    
    

    Name it files.php or so and then you have a generic PHP downloader which you can access by for example http://example.com/files/foo.pdf, http://example.com/files/bar.zip, etcetera.

    Hope this helps.

提交回复
热议问题