Simo
Simo

Reputation: 2414

How to make link/button downloadable?

SO here is the situation: I have a dynamic webpage. There is a form with "select", followed by a link (or a button). When a user clicks on the link:

  1. If the select option is "display", then the data (fed through AJAX via JQuery) will be displayed. This is DONE, -- NO PROBEM.

  2. If the option is download, then how do I make the data downloadable with the click on the link (or button)????

The result returned from AJAX is just CSV text in case of "download" option. It's not a file, just a javascript String. What do I need to do to turn it into a downloadable file?

Upvotes: 0

Views: 1344

Answers (3)

Michael
Michael

Reputation: 1

You should look at this example.

http://drupal.org/node/417866

If your running Apache it will change the way each directory is controlled so you dont have to put it in code. you just put it in a location that the .htaccess controls the way the information is delivered to the client.

Upvotes: 0

haynar
haynar

Reputation: 6030

I would suggest you to open a new window when the "download" option is selected and use appropriate header on the server side to tell the browser that this content should be downloaded into file instead of showing it in window. The header in mainly depends on what you want to download, for example with CSV using PHP (as I don't know what server-side language do you use)

<?php
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"my-data.csv\"");

// output the content of your file here

?>

Upvotes: 0

Tats_innit
Tats_innit

Reputation: 34107

Try this: http://jsfiddle.net/vpnQe/

Feel free to play around, hope it helps your need :)

code

var URL = window.webkitURL || window.URL;
var BlobBuilder = window.WebKitBlobBuilder || window.MozBlobBuilder || window.BlobBuilder;

var url;

$("button").click(function() {
    if (url) URL.revokeObjectURL(url);
    var bb = new BlobBuilder();
    bb.append("it works!");
    var file = bb.getBlob("text/plain");
    url = URL.createObjectURL(file);
    $("a[download]").attr("href", url);

    var evt = document.createEvent('MouseEvents');
    evt.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
    $("a[download]")[0].dispatchEvent(evt);
});​

HTML

<article>
    <button type="button">create url, put it in below link, and click it</button><br/>
    <a download="test.txt">Download as text.txt</a>
</article>
<footer>
<ul>
    <li><a href="https://developer.mozilla.org/en/Document_Object_Model_(DOM)/window.URL.createObjectURL">window.URL.createObjectURL</a></li>
    <li><a href="http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download">a[download]</a></li>
</ul>
</footer>​

Upvotes: 3

Related Questions