Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force browser to open file instead of prompting download

Tags:

html

hyperlink

When clicking a PDF link in Firefox and Chrome, the file will sometimes be opened for in-browser viewing and sometimes prompt a "Save as" dialog.

If I wanted to force the link to always prompt a download I could use the download HTML5 attribute.

However, I want to do the opposite. I.e., force the links to always be viewed in the browser.

Sort of an inverse download attribute. Is there such a thing? :)

I'd prefer to not modify response headers when serving PDF documents - I want to be able to specify in markup what the browser behavior should be.

Thanks!

like image 878
Ted Nyberg Avatar asked Oct 08 '13 20:10

Ted Nyberg


People also ask

How do I get browser to open instead of download?

You have to download the file type once, then right after that download, look at the status bar at the bottom of the browser. Click the arrow next to that file and choose "always open files of this type". DONE. Now the file type will always OPEN using your default program.

How do I force Chrome to open files instead of saving?

Clicking the dropdown menu only gives you additional options. Always open files of this type. This changes the default setting so instead of saving the file, it will open it in the default program, then let you choose whether or not to save the file.

How do I force a PDF to open in browser instead of download?

At the top right, click More Settings. At the bottom, click Show advanced settings. Under “Privacy”, click Content settings. Under “PDF Documents," check the box next to "Open PDF files in the default PDF viewer application.” (Uncheck this box if you want PDFs to open automatically when you click them.)


1 Answers

You can achieve that by setting the appropriate header (for instance, in case of PDF, the header will be Content-type: application/pdf;

With this header, the browser will know the mime-type of the file and display it if it is compatible with it.

Here you can see the headers for a PDF.
As a hint, what I like to do is to use some sort of controller (in case you are using a backend language) that handles the download. Hence, to download myNewProject.pdf I do

<a href='download.php?file=myNewProject.pdf&viewInBrowser=1'>Download!</a>

Then I can set the appropriate headers depending on the file type, or if I want to force download or view it in the browser...

like image 120
Nico Avatar answered Oct 05 '22 15:10

Nico