By designer-trying-coding

2010-09-27 09:28:05 8 Comments

I have some big size PDF catalogs at my website, and I need to link these as download. When I googled, I found such a thing noted below. It should open the "Save As..." popup at link click...

    <meta name="content-disposition" content="inline; filename=filename.pdf">

But it doesn't work :/ When I link to a file as below, it just links to file and is trying to open the file.

    <a href="filename.pdf" title="Filie Name">File name</a>

UPDATE (according to answers below):

As I see there is no 100% reliable cross-browser solution for this. Probably the best way is using one of the web services listed below, and giving a download link...


@NowLiveLove 2018-01-05 08:25:54

I just used this, but I don't know if it works across all browsers.

It works in Firefox:

<a href="myfile.pdf" download>Click to Download</a>

@usr2564301 2018-01-05 10:08:18

That is suggested, and with more background information, in an earlier answer.

@Pedro Lobito 2018-05-16 08:56:02

Why did you post the exact same solution posted 3 years ago?

@mljm 2017-06-09 15:37:13

I just had a very similar issue with the added problem that I needed to create download links to files inside a ZIP file.

I first tried to create a temporary file, then provided a link to the temporary file, but I found that some browsers would just display the contents (a CSV Excel file) rather than offering to download. Eventually I found the solution by using a servlet. It works both on Tomcat and GlassFish, and I tried it on Internet Explorer 10 and Chrome.

The servlet takes as input a full path name to the ZIP file, and the name of the file inside the zip that should be downloaded.

Inside my JSP file I have a table displaying all the files inside the zip, with links that say: onclick='download?zip=<%=zip%>&csv=<%=csv%>'

The servlet code is in

package myServlet;

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class
public class download extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
        PrintWriter out = response.getWriter(); // now we can write to the client

        String filename = request.getParameter("csv");
        String zipfile = request.getParameter("zip");

        String aLine = "";

        response.setHeader( "Content-Disposition", "attachment; filename=" + filename); // Force 'save-as'
        ZipFile zip = new ZipFile(zipfile);
        for (Enumeration e = zip.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            if(entry.toString().equals(filename)) {
                InputStream is = zip.getInputStream(entry);
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"), 65536);
                while ((aLine = br.readLine()) != null) {

To compile on Tomcat you need the classpath to include tomcat\lib\servlet-api.jar or on GlassFish: glassfish\lib\j2ee.jar

But either one will work on both. You also need to set your servlet in web.xml.

@yucer 2016-09-25 17:53:08

A server-side solution is more compatible, until the "download" attribute is implemented in all the browsers.

One Python example could be a custom HTTP request handler for a filestore. The links that point to the filestore are generated like this:

Here is the code:

class HTTPFilestoreHandler(SimpleHTTPRequestHandler):

    def __init__(self, fs_path, *args):
        self.fs_path = fs_path                          # Filestore path
        SimpleHTTPRequestHandler.__init__(self, *args)

    def send_head(self):
        # Overwrite SimpleHTTPRequestHandler.send_head to force download name
        path = self.path
        get_index = (path == '/')
        self.log_message("path: %s" % path)
        if '/download_as/' in path:
            p_parts = path.split('/download_as/')
            assert len(p_parts) == 2, 'Bad download link:' + path
            path, download_as = p_parts
        path = self.translate_path(path )
        f = None
        if os.path.isdir(path):
            if not self.path.endswith('/'):
                # Redirect browser - doing basically what Apache does
                self.send_header("Location", self.path + "/")
                return None
                return self.list_directory(path)
        ctype = self.guess_type(path)
            f = open(path, 'rb')
        except IOError:
            self.send_error(404, "File not found")
            return None
        self.send_header("Content-type", ctype)
        fs = os.fstat(f.fileno())
        self.send_header("Expires", '0')
        self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
        self.send_header("Cache-Control", 'must-revalidate, post-check=0, pre-check=0')
        self.send_header("Content-Transfer-Encoding", 'binary')
        if download_as:
            self.send_header("Content-Disposition", 'attachment; filename="%s"' % download_as)
        self.send_header("Content-Length", str(fs[6]))
        self.send_header("Connection", 'close')
        return f

class HTTPFilestoreServer:

    def __init__(self, fs_path, server_address):
        def handler(*args):
            newHandler = HTTPFilestoreHandler(fs_path, *args)
            newHandler.protocol_version = "HTTP/1.0"
        self.server = BaseHTTPServer.HTTPServer(server_address, handler)

    def serve_forever(self, *args):

def start_server(fs_path, ip_address, port):
    server_address = (ip_address, port)
    httpd = HTTPFilestoreServer(fs_path, server_address)

    sa = httpd.server.socket.getsockname()
    print "Serving HTTP on", sa[0], "port", sa[1], "..."

@manish1706 2016-03-04 19:10:45

Just put the below code in your .htaccess file:

AddType application/octet-stream .csv
AddType application/octet-stream .xls
AddType application/octet-stream .doc
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .mov
AddType application/octet-stream .pdf

Or you can also do trick by JavaScript

element.setAttribute( 'download', whatever_string_you_want);

@Peter Mortensen 2018-03-28 19:57:02

Doesn't this presume the web server is Apache?

@Sharad Gautam 2015-04-01 12:10:57

Try adding this line to your .htaccess file.

AddType application/octet-stream .pdf

I hope it'll work as it is browser independent.

@Nathan Hornby 2015-10-15 12:42:00

I'd be interested to know why this has been downvoted - it's one of the simplest methods and works:…

@Abandoned Cart 2017-06-11 15:19:23

People try to modify the core functionality of a server on free hosting sites and then downvote because they can't get it to work. Every other solution will have caveats because it is a "hack" to replace this.

@Brad 2017-11-14 06:05:24

I'm downvoting it because it's the wrong solution to the problem. It's a bad idea to mess with types of resources.

@PoloHoleSet 2018-01-26 17:40:04

@NathanHornby - I didn't downvote it, but this would not work for any Windows hosted site, since they don't use .htaccess.

@JBH 2018-02-15 00:12:05

I didn't downvote, but this solution blindly affects ALL files of that suffix. It's indiscriminate and therefore won't be appropriate in all cases.

@Peter Mortensen 2018-03-28 19:54:56

It may be browser independent, but isn't it dependent on the web server being Apache?

@Tony 2013-10-17 01:34:27

I had this same issue and found a solution that has worked great so far. You put the following code in your .htaccess file:

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment

It came from Force a File to Download Instead of Showing Up in the Browser.

@goodeye 2014-06-27 18:04:20

This worked well, since I had a particular document directory for downloads. I omitted the ForceType, just to let the types stay as-is. I also didn't need the case-insensitive; mine seems to be case-insensitive already. I added a couple extra types, including optional-x for the old/new Office extensions: <FilesMatch "\.(pdf|xlsx?|docx?)$">

@bwright 2015-07-31 06:22:04

This worked wonderfully, even in OSX Safari, where as other answers (including the accepted one, as one commenter pointed out there) are limited to certain browsers which support the given HTML feature. This one seems more ideal to me since it worked across the board, though it does require higher-level access to the server configuration files.

@Michael Fever 2015-09-10 14:42:10

You could put that right in your apache.conf file as well, I don't use .htaccess as it takes more resources.

@PoloHoleSet 2018-01-26 17:38:19

How would a Windows-hosted web site implement this, since they can't read htaccess files?

@Peter Mortensen 2018-03-28 19:25:23

Only for Apache?

@Ayush Gupta 2013-06-24 16:10:57

From an answer to Force a browser to save file as after clicking link:

<a href="path/to/file" download>Click here to download</a>

@Sygmoral 2014-09-05 22:48:18

At the time of this comment, the download attribute is limited to Chrome, Firefox and Opera. Even recent versions of IE and Safari do not support it. For future support: check !

@Yster 2015-05-26 11:55:14

Netbeans error checking complains about it, but it seems to work fine. You can specify a preliminary name for the new file like so: download="myFile.txt"

@user1641172 2016-11-30 16:24:53

This works in Edge at the time of writing this comment, and seems like the only way possible to stop hyperlinked PDFs opening in Edge's very poor attempt at a PDF viewer.

@Apostolos 2017-05-06 07:11:19

... Doesn't even work with Firefox. Bad reply.

@S.I. 2017-09-29 05:07:19

At the time of this comment, I've tested it on Chrome, Opera, Edge, Mozilla. All latest. Is working on all except on Mozilla.

@jean-baptiste 2018-05-19 14:39:36

This only works for same-origin links, as mentioned on If your links are cross-origin, your only option (for now) is to force the response type to "application/octet-stream", as many answers suggest. If you don't have access to the server, then you can try to proxy it and set the response header manually.

@user1156544 2018-08-13 17:11:45

@jean-baptiste agree... And a bit absurd restriction, since it greatly limits functionality whereas there are many ways to circumvent the presume "protection"

@User 2013-01-30 23:52:20

I found a very simple solution for Firefox (only works with a relative rather than a direct href): add type="application/octet-stream":

<a href="./file.pdf" id='example' type="application/octet-stream">Example</a>

@Kode 2016-01-05 17:27:02

This worked for me.

@Joojoo 2012-07-02 17:59:04

With large PDF files the browser hangs. In Mozilla, menu ToolsOptionsApplications, then next to the content type Adobe Acrobat document. In the Action drop down, select Always ask.

This did not work for me, so what worked was:

Menu Tools* → Add-onsAdobe Acrobat (Adobe PDF plugin for Firefox) → DISABLE. Now I am able to download e-books!

@Mark 2012-10-11 08:06:24

did you read the question? this is not a cross browser answer

@Nathan Hornby 2015-10-15 12:44:14

@mark it's also instructions for a user to prompt forced downloads of PDFs, not a website owner.

@Ashay 2010-09-27 09:42:14

Generally it happens, because some browsers settings or plug-ins directly open PDF in the same window like a simple web page.

The following might help you. I have done it in PHP a few years back. But currently I'm not working on that platform.

    if (isset($_GET['file'])) {
        $file = $_GET['file'];
        if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) {
            header('Content-type: application/pdf');
            header("Content-Disposition: attachment; filename=\"$file\"");
    else {
        header("HTTP/1.0 404 Not Found");
        echo "<h1>Error 404: File Not Found: <br /><em>$file</em></h1>";

Save the above as download.php.

Save this little snippet as a PHP file somewhere on your server and you can use it to make a file download in the browser, rather than display directly. If you want to serve files other than PDF, remove or edit line 5.

You can use it like so:

Add the following link to your HTML file.

<a href="download.php?file=my_pdf_file.pdf">Download the cool PDF.</a>

Reference from: This blog

@pbarney 2016-08-17 15:34:24

This appears to be a nice way to serve up every single file on your server to anyone who's paying attention. download.php?file=database_password_file.php for example.

@sushil bharwani 2010-09-27 09:37:08

If you have a plugin within the browser which knows how to open a PDF file it will open directly. Like in case of images and HTML content.

So the alternative approach is not to send your MIME type in the response. In this way the browser will never know which plugin should open it. Hence it will give you a Save/Open dialog box.

@Karel Petranek 2010-09-27 09:48:04

That's hard to achieve because it's the server that sends the mime type and when linking directly to a PDF file, you cannot change the headers.

@Bonnie 2015-04-23 16:00:43

After the file name in the HTML code I add ?forcedownload=1

This has been the simplest way for me to trigger a dialog box to save or download.

@acctman 2015-06-02 10:31:29

this works in IE 11 and 10

@gothy 2015-06-11 11:03:36

Didn't work for me in IE11 :(

@Julius 2015-03-02 13:05:54

A very easy way to do this, if you need to force download for a single link on your page, is to use the HTML5 download-attribute in the href-link.


with this you can rename the file that the user will download and at the same time it forces the download.

There has been a debate whether this is good practise or not, but in my case I have an embedded viewer for a pdf file and the viewer does not offer a download link, so i have to provide one separately. Here I want to make sure the user does not get the pdf opened in the web browser, which would be confusing.

This won't necessary open the save as-dialog, but will download the link straight to the preset download destination. And of course if your doing a site for someone else, and need them to write in manually attributes to their links is probably a bad idea, but if there is way to get the attribute into the links, this can be a light solution.

@DrWaky 2014-02-03 12:50:49

<a href="file link" download target="_blank">Click here to download</a>

It works for me in Firefox and Chrome.

@Rakesh Waghela 2014-04-09 11:27:45

Most practical answer !

@Sygmoral 2014-09-05 22:52:58

It's exactly the same as the current top answer though, from Ayush Gupta in 2013. The target="_blank" may make it slightly more usable for non-supporting browsers, though (PDFs then open in a new window/tab, rather than overwriting the current page).

@casraf 2017-04-18 09:43:11

For me, target="_blank" was necessary as download only failed to trigger the download properly (Chrome)

@weaknespase 2018-04-09 06:36:15

If you give a string in the download attribute, it will be used as file name. I'm using it in userscripts all the time.

@Karel Petranek 2010-09-27 09:45:30

Meta tags are not a reliable way to achieve this result. Generally you shouldn't even do this - it should be left up to the user/user agent to decide what do to with the content you provide. The user can always force their browser to download the file if they wish to.

If you still want to force the browser to download the file, modify the HTTP headers directly. Here's a PHP code example:

$path = "path/to/file.pdf";
$filename = "file.pdf";
header('Content-Transfer-Encoding: binary');  // For Gecko browsers mainly
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
header('Accept-Ranges: bytes');  // Allow support for download resume
header('Content-Length: ' . filesize($path));  // File size
header('Content-Encoding: none');
header('Content-Type: application/pdf');  // Change the mime type if the file is not PDF
header('Content-Disposition: attachment; filename=' . $filename);  // Make the browser display the Save As dialog
readfile($path);  // This is necessary in order to get it to actually download the file, otherwise it will be 0Kb

Note that this is just an extension to the HTTP protocol; some browsers might ignore it anyway.

@Matthew Wilson 2010-09-27 10:00:46

In practice I believe this is widely implemented.

@casraf 2012-06-16 18:47:27

This is the best solution, hassle free and works. You can directly download any file type using this method. +1

@Julian Reschke 2012-09-15 07:03:22

Content-Transfer-Encoding does not exist in HTTP. Content-Encoding: none is useless.

@T.Todua 2014-05-12 10:52:11

MAKE A NOTE in your answer, that IF file is from external server/domain, then this answer may not be solution...

@Hendrik 2016-07-14 18:06:28

I'd like to add that I have had this or similar code fail on certain servers when files get large (>80 MB in my case). Using ob_end_flush() didn't help either.

@PoloHoleSet 2018-01-26 17:34:51

"it should be left up to the user/user agent to decide what do to with the content you provide" - depends on what kind of user you have. We have employee users, and also for customers for some of our .pdf forms where the behavior, especially printing behavior, varies widely from browser to browser and differs greatly from a pdf reader app in how it renders the images. Items disappear, thick field borders are conjured out of thin air...... we need our users to open specific pdfs from a pdf app, not in the browser.

@Mr. Bungle 2010-11-12 03:53:31

A really simple way to achieve this, without using external download sites or modifying headers etc. is to simply create a ZIP file with the PDF inside and link directly to the ZIP file. This will ALWAYS trigger the Save/Open dialog, and it's still easy for people to double-click the PDF windows the program associated with .zip is launched.

BTW great question, I was looking for an answer as well, since most browser-embedded PDF plugins take sooo long to display anything (and will often hang the browser whilst the PDF is loading).

@CodeWarrior 2014-02-07 16:11:08

Terrible usability. Many end users wouldn't know what to do with a zip file.

@elrado 2015-10-21 06:50:59

Sometimes simple solutioans are the best solutions!

@Arnaud Weil 2017-02-15 13:18:27

Not a good solution. I have exactly that problem with Firefox and a ZIP file. What should I do? ZIP the file? In that case, modifying the HTTP headers could be a solution but I have no access to that.

Related Questions

Sponsored Content

20 Answered Questions

[SOLVED] Recommended way to embed PDF in HTML?

  • 2008-11-14 23:55:13
  • Daniel Silveira
  • 1143009 View
  • 986 Score
  • 20 Answer
  • Tags:   html pdf

4 Answered Questions

[SOLVED] Open link in new tab or window

29 Answered Questions

[SOLVED] How to create an HTML button that acts like a link?

8 Answered Questions

[SOLVED] Returning a file to View/Download in ASP.NET MVC

30 Answered Questions

[SOLVED] Convert HTML + CSS to PDF with PHP?

32 Answered Questions

[SOLVED] Convert HTML to PDF in .NET

  • 2009-02-19 10:21:22
  • SandHurst
  • 434623 View
  • 353 Score
  • 32 Answer
  • Tags:   c# html pdf itextsharp

3 Answered Questions

[SOLVED] Cannot display HTML string

15 Answered Questions

[SOLVED] How do I reformat HTML code using Sublime Text 2?

3 Answered Questions

[SOLVED] Download pdf from href link issue

0 Answered Questions

Opening PDF from a POST in a new tab

Sponsored Content