3

I know how to setup a href and a download attribute on an anchor to allow a user to download data as a file.

However, a client has requested that one link download two files together AND not be zipped! Don't ask me why!

Looking online I found the following solutions:

1) create 2 iframes on the fly and in each's form set its GET to the location of one of the files on the server, then run a form submit...here

2) A variation of (1) using a JQuery plugin..here

3) Opening popup windows. (not worth the link)

I'm wondering if I can handle this on the JS side? In the same App, I'm exporting data to CSV with the following code:

$elm.attr('href', 'data:text/csv;charset=utf8,' + encodeURIComponent(_str)).attr('download', fileName);

Where _str is a flattened two dimensional array.

Can I somehow trail or attach a second file to that?

Community
  • 1
  • 1
Sam Hammamy
  • 10,819
  • 10
  • 56
  • 94

1 Answers1

0

You can create links on the fly and fire navite click event.

function downloadAll(files){
    if(files.length == 0) return;
    file = files.pop();
    var theAnchor = $('<a />')
        .attr('href', file[1])
        .attr('download',file[0]);
    theAnchor[0].click(); 
    theAnchor.remove();
    downloadAll(files);
}

$('a.download-csv').on('click', function(){
    downloadAll([

        ['file1.csv', 'data:text/csv;charset=utf8,'+ 
                     encodeURIComponent('my,csv,file\and,so,on')],

        ['file2.csv', 'data:text/csv;charset=utf8,'+ 
                     encodeURIComponent('my,csv,file\and,so,on')],

        ['file3.csv', 'data:text/csv;charset=utf8,'+ 
                     encodeURIComponent('my,csv,file\and,so,on')]

    ]);
});

Here you can find the fiddle with a working demo.

Here is the article on my web site with all the details