Do not view PDF inside the browser

Asked

Viewed 807 times

3

I have the following anchor:

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

By clicking this link automatically the browser recognizes that it is PDF and views it. As below: inserir a descrição da imagem aqui

Otherwise, I would like when the click on the link was triggered to start downloading the browser.

  • What is your server-side language?

2 answers

7

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

But in HTML5 there is a new attribute downloadwhich does just that, in other words, tells the browser that this link is for download. At the value of this new field you can enter the name of the file or not defenir 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 downloadoverrides the name of the file that was in the href would be:

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

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

  • You could explain that part better: "The common answer to this is that you should change the link to instead of being a file to use a server-side page (PHP for example) and set up http header to force the download."

  • 2

    @Luitame, when the server sends data to the browser it has a "header" (header) that helps the browser to know what to do with the information. In this header, and depending on what language you have on the server side, you can specify that it is a file to save, not to open. Hence my question in the comments above: Qual é a sua linguagem do lado do servidor?

  • The language is PHP :)

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);

?>

Instead 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. It 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 will follow the binary standard to download, thus not damaging the final file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.