Arnaud
Arnaud

Reputation: 151

Download in JS a ZIP file created in PHP

I want to download a zip file created via a PHP method. When user clicks on a "download" icon, the zip is created and should be automatically downloaded.

The zip creation works fine. The PHP method ends like this:

    header("Content-disposition: attachment;filename=\"archive.zip\"");
    header('Content-Type: application/zip');
    header('Content-Length: ' . filesize($path_archive));
    readfile($path_archive);
    return;

This is the AJAX method in my JS file. path is needed for my function to create the archive.

    $.ajax({
        url: "url_of_PHP_method",
        data : { path : path },
        type: 'GET',
        success: function (data) { 
            var uriContent = "data:application/zip;" + data;
            var myWindow = window.open(uriContent, "archive.zip");
            myWindow.focus();
        }
    }); 

Unfortunately, the downloaded file is called "download". It has no extension and even if I rename it with a .zip extension, there's an error opening it:

End-of-central-directory signature not found.

Hae you guys encountered the same issue ? I've found similar questions on this site but none faced the same situation. Thanks in advance :)

Upvotes: 2

Views: 3801

Answers (1)

raidenace
raidenace

Reputation: 12836

Ajax cannot be used to download a file because of security issues. You can create a regular hyperlink to your php script that does the action and the browser will show up the save download dialog without leaving the current page you are in.

Sample code:

<script type="text/javascript">
location.href = "url_of_PHP_method";
</script>

Upvotes: 2

Related Questions