7

In my project site, if I click on a link, the PDF opens in a new or parent window. Well I want a box to appear that prompts the user to download the file instead of opening it.

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

My server is PHP based.

jonsca
  • 10,218
  • 26
  • 54
  • 62
Jitendra Vyas
  • 148,487
  • 229
  • 573
  • 852

6 Answers6

14

Since your edit states that you're 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');
?>
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
9

Since you've tagged it .NET, I'd 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();
Sam Hanley
  • 4,707
  • 7
  • 35
  • 63
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
3

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

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

Also, set the following:

Response.AppendHeader( "content-disposition", "attachment; filename=" + name );
cjk
  • 45,739
  • 9
  • 81
  • 112
1

You can't do it via javascript, you need server side implementation.

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

Community
  • 1
  • 1
o.k.w
  • 25,490
  • 6
  • 66
  • 63
1

http://aspalliance.com/259_Downloading_Files__Forcing_the_File_Download_Dialog

Gregoire
  • 24,219
  • 6
  • 46
  • 73
0

If you are getting a corrupted 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.

Miguel
  • 395
  • 1
  • 5
  • 13