开发者

PDF files opening up in browser

开发者 https://www.devze.com 2023-01-18 10:45 出处:网络
One of the app that I coded was giving option to download everytime I click on a pdf file. Now it opens up in a browser. I did开发者_JS百科n\'t change any code. How can I make it so it only let them d

One of the app that I coded was giving option to download everytime I click on a pdf file. Now it opens up in a browser. I did开发者_JS百科n't change any code. How can I make it so it only let them download and not open up in browser?


I can think of two ways of doing this: You can either simply ZIP the PDF files, which would then force a download, or you could write a script that would serve the requested files as downloadable attachments. Not sure what language is your app written in, but in PHP you could do it like this:

download.php

<?php   
if (isset($_GET['file'])) { 
    $file = $_GET['file'];
        if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file))  { 
            header('Content-type: application/pdf');  
            header("Content-Disposition: attachment; filename=\"$file\"");   
            readfile($file); 
        } 
    } else { 
    header("HTTP/1.0 404 Not Found"); 
    echo "<h1>Error 404: File Not Found: <br /><em>$file</em></h1>"; 
} 
?> 

and then you would link to your pdf files like:

<a href="download.php?file=my_pdf_file.pdf">Download the cool PDF.</a>

Found on this forum post.

Hope this helps.


Browsers have plugins that can open up your pdf files in browsers themselves when you dont have these plugins they download it. One way you can still achieve it is while sending the file for download dont tell browser the Mime Type of the response hence this way plugin wont know that there is a pdf file to open and would still let u download it.

try sending following header Content-Disposition: attachment; filename=genome.pdf; modification-date="Wed, 12 February 1997 16:29:51 -0500";

0

精彩评论

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