TunaFFish
TunaFFish

Reputation: 11302

jQuery download a zipfile from a button?

Quite embarrassing how much time I spend trying to get to download a zipfile from a button....

<button type='button' id='button-download'>download zipfile</button>


$("#button-download").live("click", function() {
    $.get("http://localhost/admin/zip/002140.zip"); // doesn't work?
})

I need something bullet proof here, that's why I ask here, thanks.

Upvotes: 8

Views: 26167

Answers (4)

TheCarver
TheCarver

Reputation: 19723

Bit late to the party but thought I'd share my solution as nobody else has.

You can have the best of both worlds; a simple HTML link and a JS function, without losing the non-JS users.

<a id="download" href="http://www.example.com/download.zip">Download</a>

$("#download").on("click", function(e) {

    // cancel the link's original functionality
    e.preventDefault();

    // do something before downloading
    alert("Thanks for downloading!");

    // download file
    location.href = "http://www.example.com/download.zip";

});

Upvotes: 1

bobince
bobince

Reputation: 536587

Use a plain:

<a href="http://localhost/admin/zip/002140.zip" id="button-download">download zipfile</a>

link. Then it'll work fine (“bullet proof” even) without JavaScript available. It also offers more of the traditional affordances users might expect from a download link, such as right-click-save-as, or drag-and-drop.

You can of course use CSS to make it look like a button instead of a link. But what it actually is, is a link. So that's how it should be marked up.

Upvotes: 7

Kerry Jones
Kerry Jones

Reputation: 21848

That is sending an AJAX request.

I haven't tried this, but it should work in theory. If you try to go to a location of a file that is downloaded, it prompts you to download rather than take you to that page.

<button type='button' id='button-download'>download zipfile</button>


$("#button-download").live("click", function() {
    window.location = "http://localhost/admin/zip/002140.zip";
})

Upvotes: 1

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827734

You should set the location.href property to cause navigation:

$("#button-download").live("click", function() {
  location.href = "http://localhost/admin/zip/002140.zip";
});

You could also have a simple <a> element, styled as if it were a button, in that way even the users who have JavaScript disabled will be able to download the file.

Upvotes: 5

Related Questions