Download File Using JavaScript/jQuery

Viewed 1563323

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?

32 Answers

2019 modern browsers update

This is the approach I'd now recommend with a few caveats:

  • A relatively modern browser is required
  • If the file is expected to be very large you should likely do something similar to the original approach (iframe and cookie) because some of the below operations could likely consume system memory at least as large as the file being downloaded and/or other interesting CPU side effects.

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(resp => resp.blob())
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    // the filename you want
    a.download = 'todo-1.json';
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    alert('your file has downloaded!'); // or you know, something with better UX...
  })
  .catch(() => alert('oh no!'));

2012 original jQuery/iframe/cookie based approach

I have created the jQuery File Download plugin (Demo) (GitHub) which could also help with your situation. It works pretty similarly with an iframe but has some cool features that I have found quite handy:

  • Very easy to setup with nice visuals (jQuery UI Dialog, but not required), everything is tested too

  • User never leaves the same page they initiated a file download from. This feature is becoming crucial for modern web applications

  • successCallback and failCallback functions allow for you to be explicit about what the user sees in either situation

  • In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for an example of this. Hope this helps someone!

Here is a simple use case demo using the plugin source with promises. The demo page includes many other, 'better UX' examples as well.

$.fileDownload('some/file.pdf')
    .done(function () { alert('File download a success!'); })
    .fail(function () { alert('File download failed!'); });

This could be helpful if you are not require to navigate another page. This is base javascript function, so can be used in any platform where backend is in Javascript

window.location.assign('any url or file path')

I ended up using the below snippet and it works in most browsers, not tested in IE though.

let data = JSON.stringify([{email: "test@domain.com", name: "test"}, {email: "anothertest@example.com", name: "anothertest"}]);

let type = "application/json", name = "testfile.json";
downloader(data, type, name)

function downloader(data, type, name) {
 let blob = new Blob([data], {type});
 let url = window.URL.createObjectURL(blob);
 downloadURI(url, name);
 window.URL.revokeObjectURL(url);
}

function downloadURI(uri, name) {
    let link = document.createElement("a");
    link.download = name;
    link.href = uri;
    link.click();
}

Update

function downloadURI(uri, name) {
    let link = document.createElement("a");
    link.download = name;
    link.href = uri;
    link.click();
}

function downloader(data, type, name) {
    let blob = new Blob([data], {type});
    let url = window.URL.createObjectURL(blob);
    downloadURI(url, name);
    window.URL.revokeObjectURL(url);
}

You can also use the package fs-browsers.
It has nice and easy download method for client-side.
It goes like this:

import { downloadFile } from 'fs-browsers';
downloadFile(url-to-the-file);

Maybe just have your javascript open a page that just downloads a file, like when you drag a download link to a new tab:

Window.open("https://www.MyServer.
Org/downloads/ardiuno/WgiWho=?:8080")

With the opened window open a download page that auto closes.

You can simply make use of the Download attribute in HTML. Using good ol' Javascript, you can use this feature to download the file directly. The download attribute of the anchor tag should point to the link where the file to be downloaded is hosted.

Firstly, point the URL to your resource path:

var url = 'your url goes here';

Create an anchor tag, with the needed attributes as below:

var elem = document.createElement('a');
elem.href = url;
elem.download = url;
elem.id="downloadAnchor";

Append the anchor tag to the body element of the webpage.

document.body.appendChild(elem);

Now trigger the click event programmatically. Clicking on the anchor tag will trigger the download.

$('#downloadAnchor').click();

Putting it all together:

var url = 'your url goes here';
var elem = document.createElement('a');
elem.href = url;
elem.download = url;
elem.id="downloadAnchor";
document.body.appendChild(elem);
$('#downloadAnchor').click();

Additional Information: Nothing fancy in the above code, just client-side JavaScript which works from Chrome Devtools' Console, but powerful and also opens up a lot of possibilities like webpage crawling.

For e.g. the following chunk of code executed in the Devtools console will open all the links in the page in a new tab: Just goto this webpage , open devtools and run this script in the browser console and watch the power of JavaScript unfurl. (Note: The below code is purely for educational purposes only.)

Make sure you enable pop-ups for that site, else your anchor clicks will get disabled by the default pop-up blocker.

var links = document.getElementsByClassName("_3ATBKe");
for(var i=0;i<links.length;i++){
    var title = document.getElementsByClassName("_3ATBKe")[i].firstElementChild.firstElementChild.innerText.replaceAll('|','-').replaceAll(':','x');
    console.log('Opening..'+title);
    links[i].firstElementChild.click();
}

Note: This is not just limited to anchor clicks, you can download almost anything you find on your webpage. If something (image, audio, video) loads on your webpage, you can probably write a script to download it, even if the provision is not provided to you from the UI.

for me this is working ok tested in chrome v72

function down_file(url,name){
var a = $("<a>")
    .attr("href", url)
    .attr("download", name)
    .appendTo("body");
a[0].click();
a.remove();
}

down_file('https://www.useotools.com/uploads/nulogo[1].png','logo.png')

There are so many little things that can happen when trying to download a file. The inconsistency between browsers alone is a nightmare. I ended up using this great little library. https://github.com/rndme/download

Nice thing about it is that its flexible for not only urls but for client side data you want to download.

  1. text string
  2. text dataURL
  3. text blob
  4. text arrays
  5. html string
  6. html blob
  7. ajax callback
  8. binary files
let args = {"data":htmlData,"filename":exampleName}

To create a HTMl file and download

window.downloadHTML = function(args) {
var data, filename, link;
var csv = args.data;
if (csv == null) return;
filename = args.filename || 'report.html';
data = 'data:text/html;charset=utf-8,' + encodeURIComponent(csv);
console.log(data);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);}

To create and download a CSV

window.downloadCSV = function(args) {
var data, filename, link;
var csv = args.data;
if (csv == null) return;
filename = args.filename || 'report.csv';
if (!csv.match(/^data:text\/csv/i)) {
    csv = 'data:text/csv;charset=utf-8,' + csv;
}
data = encodeURI(csv);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

}

Only pass link of the file. It will download the file with it's original name.

function downloadFileWithLink(href) {
    var link = document.createElement("a");
    let name = (href?.split("/") || [])
    name = name[name?.length-1]
    link.setAttribute('download', name);
    link.href = href;
    document.body.appendChild(link);
    link.click();
    link.remove();
}

You have to do it from two sides, from the server and from the client (web app).

From the server, set the header called Content-Disposition https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition

// nodejs express
  res.set('Content-Disposition', `attachment; filename="${self.creationName}"`)

With the above header, the server will tell the browser that the response is a file and it should be downloaded and saved with given name, otherwise the browser may save the file as something like "attachments (1).zip"

Next we look at the client, we create an anchor link and automatically click it.

function downloadThroughAnchorLink(downloadUrl: string, fileName: string) {
    const a = document.createElement('a')
    a.href = downloadUrl;
    // We provided a header called Content-Disposition so we dont need to set "a.download" here
    // a.download = fileName || 'download'
    a.click()
}

That should do it.

Related