开发者

PDF to download, not link to view/download

开发者 https://www.devze.com 2023-01-07 16:09 出处:网络
I am trying to make it so when you click \"download here\" a pdf file will download to the user\'s desktop. How should I go about doing 开发者_Python百科this?Use the Content-Disposition header.

I am trying to make it so when you click "download here" a pdf file will download to the user's desktop. How should I go about doing 开发者_Python百科this?


Use the Content-Disposition header.

But, please: Only do this if it is really necessary for the user to download the PDF and not open it (so that it’s just an aid for the user that he does not have to explicitly select “save file”). Don’t use it to force the user to download it although he just wants to view it.


code for a.php:

<?php
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename=file.pdf')
echo file_get_contents("file.pdf");
?>

link it in web:

 <a href="a.php">Download</a>


This is a common issue and only few people know there's a simple HTML 5 solution:

<a href="./directory/yourfile.pdf" download="newfilename">Download the pdf</a>

Where newfilename is the suggested filename for the user to save the file. Or it will default to the filename on the serverside if you leave it empty, like this:

<a href="./directory/yourfile.pdf" download>Download the pdf</a>

Compatibility: I tested this on Firefox 21 and Iron, both worked fine. It might not work on HTML5-incompatible or outdated browsers. The only browser I tested that didn't force download is IE...


What you are asking is to control browser behavior - this is not simple.

The best bet you have it to point the link to what seems like a web page (i.e. download.php?file=1) and once the browser notices it's binary data, it will ask the user what it wants to do with it. This method will most likely get the job done.

But note that this behavior cannot be guaranteed, and is highly-dependent on browser configuration.


I think that there's a <meta> tag for that. I think it's called 'nosave'. Don't go seaching the WWW for that though - I was searching and couldn't find it.

0

精彩评论

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