views:

160

answers:

2

I have a very similar requirement specified here http://stackoverflow.com/questions/1296085/download-file-using-jquery

need to start download a file when i manually calls $('a#someID').click();

But I cannot use window.href method as solution since it replaces the current page contents with the file you're trying to download. Instead I want to open the download in new window/tab. How is this possible?

+2  A: 

This thread should help

letronje
I tried this iframe method but a link `<iframe src="http://localhost/assets/9B6B5D5F-7BB8-47DD-B6BD-40CA1D7C094D.pdf" style="display: none;"></iframe>` renders in my firefox as below and no download prompt appears<html><head></head><body marginwidth='0' marginheight='0'><embed width="100%" height="100%" name="plugin" src="http://localhost/assets/9B6B5D5F-7BB8-47DD-B6BD-40CA1D7C094D.pdf" type="application/pdf"></body></html>
Mithun P
same for google chrome too
Mithun P
+2  A: 

Use this function:

var downloadURL = function(url)
{
    var iframe;
    iframe = document.getElementById("hiddenDownloader");
    if (iframe === null)
    {
        iframe = document.createElement('iframe');  
        iframe.id = "hiddenDownloader";
        iframe.style.visibility = 'hidden';
        document.body.appendChild(iframe);
    }
    iframe.src = url;   
}

The way it works is by creating an invisible iframe (only once) which can be then set to download files from the internet.

To force the browser to download a file it would otherwise be capable of rendering, you need the server to set the file's MIME Type to a nonsensical value, such as application/x-please-download-me or alternatively application/octet-stream, which is used for arbitrary binary data.

Edit: If you only want to open it in a new tab, the only way to do this is for the user to a click on a link with its target attribute set to _blank... In jQuery:

$('a#someID').attr({target: '_blank', 
                    href  : 'http://localhost/blahblah/file.pdf'}).;

Whenever that link is clicked, it will download the file in a new tab/window.

Andrew Dunn
This method is not showing the download prompt, instead it embedded the pdf file at the end of the page. Please see my comments in letronje's answer
Mithun P
A webpage cannot open a new tab automatically. To force the browser to download, get the server to send the pdf file with a nonsense MIME-type, such as application/x-please-download-me
Andrew Dunn
thanks, i was missing the MIME types
Mithun P