-1

I have a HTML page that allows user to download the file there's a button to download it, I'm using an onClick event to make an ajax call to a php script that gives the file data.

The problem is the file data is being recieved in the response but file is not dowloading.

I've already referred to this Php file download through ajax request post but is not solving my problem

HTML page


<button onClick="download()"> Download </button>

<script>
    function download {
    var url = "download"; //it is a code ignitor project hence it is just an action call.
    var path ="<?php echo $data[0]->file_path . $data[0]->file_name; ?>";
    $.post(url, {path: path}, function(result){

    });
</script>

PHP script


public function download() {
        $path = $this->input->post('path');

        if(!file_exists($path)){
            die('file not found');
        } else {

            header("Content-Disposition: attachment; filename=" . basename($path) . "");
            header("Content-Length: " . filesize($path));
            header("Content-Type: application/octet-stream;");
            readfile($path);
        }
    }

Thanks.

Nilesh Kumar
  • 343
  • 1
  • 5
  • 18

1 Answers1

1

Change the server function so it uses a get parameter. Then open a new window with the script URL.

function download() {
    var path ="<?php echo $data[0]->file_path . $data[0]->file_name; ?>";
    var url = "download?path=" + encodeURIComponent(path); //it is a code ignitor project hence it is just an action call.
    window.open(url);
});
public function download() {
    $path = $this->input->get('path');

    if(!file_exists($path)){
        die('file not found');
    } else {
        header("Content-Disposition: attachment; filename=" . basename($path) . "");
        header("Content-Length: " . filesize($path));
        header("Content-Type: application/octet-stream;");
        readfile($path);
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • This solves my problem. But I have two questions **How does the opened page closes automatically?** and **Is it safe to send the path through a `get` where it will be visible in the address bar of the browser?** – Nilesh Kumar Jun 11 '19 at 02:15
  • See https://stackoverflow.com/questions/1066452/easiest-way-to-open-a-download-window-without-navigating-away-from-the-page for other solutions. – Barmar Jun 11 '19 at 02:19
  • _“How does the opened page closes automatically?”_ - don’t open it in the first place. Use `location.href = …` instead of window.open - all modern browsers should _not_ replace the current document, if the response to the new request is one that triggers a download dialog. _“Is it safe to send the path through a get where it will be visible in the address bar of the browser?”_ - that depends on what you want it to be safe _against_ … – 04FS Jun 11 '19 at 08:31