mike23
mike23

Reputation: 1312

How to force file download upon jQuery AJAX success?

I'm generating a file dynamically in php like this :

$attachment_url = "http://www.mysite.com/file.jpg";
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="'.basename( $attachment_url ).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
readfile( $attachment_url );

This data in then passed through jQuery.ajax

I'd like to make it open a file download dialog upon success.

Right now I have this :

success: function(data, textStatus, XMLHttpRequest) {
    var win = window.open();
    win.document.write(data);
}

This does open a new window and display the raw file data. Instead I would like a download dialog to open.

Upvotes: 2

Views: 10795

Answers (1)

mts7
mts7

Reputation: 583

I'm not sure I have all the necessary information, but you could achieve the goal with 3 files.

download.php

$file = $_GET['file'];
$path = '/var/www/html/';
$attachment_url = $path.$file;

header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="'.basename( $attachment_url ).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
readfile( $attachment_url );

api.php

if (isset($_GET['generate_file'])) {
    $str = '';
    for($i = 0; $i < 10; $i++) {
        $str .= "Number $i\n";
    }
    $name = 'file.txt';
    $path = '/var/www/html/';
    file_put_contents($path.$name, $str);
    echo $name;
}

ajax.html

<script type="text/javascript">
$.ajax({
    url: '/api.php', 
    data: {
        generate_file: true
    }
})
.done(function(name) {
    $('#results').append('<a href="/download.php?file=' + name + '" id="link">' + name + '</a>');
    document.getElementById('link').click(); // $('#link').click() wasn't working for me
    $('#link').remove();
});
</script>
<div id="results"></div>

Upvotes: 6

Related Questions