Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"download" of client-side data from JS (without a new server round-trip)

Tags:

javascript

I've got a bunch of data on the client side, in JS. I want to allow the user to save that data to the local hard drive in text (CSV actually) format.

I can easily accomplish this by posting all of this data up to the server using ajax, then initiate a GET from the client to download the data. But that seems wasteful. Especially if the data is large.

The client already has the data -- I could certainly show it to them, and allow them to copy/paste it into their favorite text editor -- but that's not a very nice UI.

I want to allow them to save the data to a local file. I understand the security implications here.

I believe this is possible using dataurl, but (thank you MS), this has to work in IE7 and 8.. so that's out.

Any out-of-the-box ideas?

like image 641
desau Avatar asked Oct 14 '22 22:10

desau


2 Answers

Downloadify does this. It requires Flash.

Downloadify is a tiny JavaScript + Flash library that enables the generation and saving of files on the fly, in the browser, without server interaction.

like image 67
Pekka Avatar answered Oct 18 '22 03:10

Pekka


Won't work for this specific setup, but it's something along those lines..

http://decafbad.com/2009/07/drag-and-drop/api-demos.html#data_transfer

<!DOCTYPE HTML>
<html lang="en">
<head>
    <title>Drag and Drop --> Text File</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta http-equiv="Content-Language" content="en-us" />
    <script type="text/javascript" src="jquery.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            // Set up the draggable element.
            $('#data_transfer').bind('dragstart', function(ev) {
                if (!$(ev.target).hasClass('dragme')) return true;
                var dt = ev.originalEvent.dataTransfer;
                dt.setData('text/plain', $('#source').text());
                return true;
            });
        });
    </script>

    <style type="text/css">
        .dragme {
            border: 1px solid #000;
            background-color: #decafb;
            padding: 10px;
        }
    </style>
</head>

<body>
    <div id="data_transfer">
        <textarea id="source">Blah! I'm a textarea!</textarea>
        <p><span class="dragme" draggable="true">Drag Me to your Desktop!</span></p>
    </div>
</body>
</html>
like image 40
drudge Avatar answered Oct 18 '22 02:10

drudge