Request user to download PDF file instead of opening

On my project site, if I click the link, the PDF will open in a new or parent window. Well, I want a box to appear that prompts the user to download the file, rather than open it.

Does anyone know of a simple onClick JavaScript event that will do this in all browsers with default settings?

My server is based on PHP.

+7
javascript php apache
source share
6 answers

Since your editing claims that you are using PHP, here's how to do the same in PHP:

<?php header('Content-type: application/pdf'); header('Content-Disposition: attachment; filename="downloaded.pdf"'); readfile('original.pdf'); ?> 
+13
source share

Since you marked it with .NET, I would say this is your best solution:

 Response.ClearContent(); Response.ClearHeaders(); Response.ContentType = "application/pdf"; Response.AddHeader("Content-Disposition", "attachment;filename=download.pdf"); Response.WriteFile(Server.MapPath("~/files/myFile.pdf")); Response.Flush(); Response.Close(); 
+9
source share

Change Content-Type to application / octet-stream. However, you may find that some browsers will exit the file extension that it should open as a PDF with your favorite PDF viewer.

 Response.ContentType = "application/octet-stream"; 

Also install the following:

 Response.AppendHeader( "content-disposition", "attachment; filename=" + name ); 
+3
source share

You cannot do this with javascript, you need a server side implementation.

Here's the SO Post, which should help:
Allow user download from my site through Response.WriteFile ()

+1
source share

If you get a damaged file error, try this:

 header('Pragma: public'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Cache-Control: private', false); header('Content-Type: application/pdf'); header('Content-disposition: attachment; filename=' . basename($file)); header("Content-Transfer-Encoding: binary"); header('Content-Length: ' . filesize($file)); // provide file size header('Connection: close'); readfile($file); 

Where $file is the full path or URL of the file.

0
source share

All Articles