Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download File Using JavaScript/jQuery

I have a very similar requirement specified here.

I need to have the user's browser start a download manually when $('a#someID').click();

But I cannot use the window.href method, 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?

like image 891
Mithun Sreedharan Avatar asked Sep 20 '10 06:09

Mithun Sreedharan


People also ask

How do I download a file using JavaScript?

To ask the browser to download a file it can render, use the following header: Content-Disposition: attachment; filename="downloaded. pdf" (you can of course customize the filename as you need).

How can download PDF with button click in jQuery?

Downloading PDF File on Button Click using jQueryInside the DownloadFile JavaScript function, the URL of the File is passed as parameter to the jQuery AJAX function. Inside the jQuery AJAX function, using the XmlHttpRequest (XHR) call, the PDF file is downloaded as Byte Array (Binary Data).

How do I download a JavaScript file from a website?

open the Js script link and press ctrl+s i.e save it. Save it by any desired name and then copy it your project folder and then include it in your project files where you have included other files like jquery and css.


1 Answers

Use an invisible <iframe>:

<iframe id="my_iframe" style="display:none;"></iframe> <script> function Download(url) {     document.getElementById('my_iframe').src = url; }; </script> 

To force the browser to download a file it would otherwise be capable of rendering (such as HTML or text files), 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.

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/directory/file.pdf'}); 

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

like image 156
Randy the Dev Avatar answered Sep 28 '22 04:09

Randy the Dev