Do not view PDF inside browser

3

I have the following anchor:

   <a href="http://localhost/refazer/uploads/0503-14.pdf">Conteúdo</a>

By clicking this link the browser automatically recognizes that it is PDF and views it. As below:

Otherwise, I wanted the browser to start downloading when the browser clicked on the link.

    
asked by anonymous 14.05.2014 / 22:49

2 answers

6

The common answer to this is that you should change the link instead of being a file using a server side page (PHP for example) and setting the http header to force the download.

However in HTML5 there is a new attribute download that does this, ie tells the browser that this link is for download. In the value of this new field you can enter the name of the file or not define to use what is in the link.

 <a href="http://localhost/refazer/uploads/0503-14.pdf" download>Conteúdo</a>
                                                        ^------^

Example with a value in download that overrides the file name that was in href would be:

<a href="http://localhost/refazer/uploads/0503-14.pdf" download="ficheiro0503.pdf">Conteúdo</a>

Note: Browsers are gradually integrating the new HTML5 specifications. Today this does not work in all browsers, in a few months, or for the next year, this should be the common practice.

    
14.05.2014 / 22:57
0

The way to do it in PHP is very simple

<?php

$file_url = $_GET['file'];
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url);

?>

In place of $ _GET ['file'] you can put the file name, or a page variable. Although HTML5 has evolved a lot, not all users have evolved along with technology. There will always be people with old browsers. This will take years to disappear.

The "application / octet-stream" type indicates that it should download part by part (continuous) and "Binary" encoding indicates that it followed the binary pattern to download, thus not damaging the final file.

    
31.08.2015 / 20:14