0

I'm trying to download a file using force_download in codeigniter.

I create an AJAX call like this

$.ajax({
    type: 'POST'
    , url: '<?php echo base_url('downloadPayroll'); ?>'
    , data: { filename: filename }
});

And here is my controller

public function downloadPayroll() {
    $filename = $this->input->post('filename');
    $fileContents = file_get_contents(base_url('assets/uploads/'. $filename));

    force_download($filePath, $fileContents);
}

I know I have the correct path and filename but it doesn't download anything.

What am I doing wrong because the documentation for Download Helper is very limited.

Cronas De Se
  • 331
  • 4
  • 21

4 Answers4

0

Please try using below code. You are passing wrong variable name for force_download

$filename = $this->input->post('filename');
$fileContents = file_get_contents(base_url('assets/uploads/'. $filename)); 
$file='test.pdf';
force_download($file, $fileContents);
Nishant Nair
  • 1,999
  • 1
  • 13
  • 18
0

Just a note to anyone else who may be having this problem: Make sure you have a file extension on the filename you supply for the first argument to force_download().

CodeIgniter uses this to set the MIME type, and it doesn't seem to work without.

for more CodeIgniter - force_download() problem.

$name = 'myfile.txt';//file extension is required
force_download($name, NULL);//if you dont want to send data set NULL

And Don't forget to load download helper first.

$this->load->helper('download');
Community
  • 1
  • 1
Hikmat Sijapati
  • 6,869
  • 1
  • 9
  • 19
0

there is no way to download a file via an ajax request like that - try this instead

your JS File

$.ajax({
    type: 'POST'
    , url: '<?php echo base_url('downloadPayroll'); ?>'
    , data: { filename: filename },

    success: function(strUrl)
    {
        var link = document.createElement('a');
        link.style = "display: none";
        link.href = strUrl;
        document.body.appendChild(link);
        link.click();
        setTimeout(function () {
            document.body.removeChild(link);
        }, 5000);   
    }
});

Your Controller:

public function downloadPayroll() 
{
    $filename = $this->input->post('filename');
    echo base_url('assets/uploads/'. $filename);
}
Atural
  • 5,389
  • 5
  • 18
  • 35
0

you are missing the helper

public function downloadPayroll() {
$filename = $this->input->post('filename');
$fileContents = file_get_contents(base_url('assets/uploads/'. $filename));

$this->load->helper( 'download' );

force_download($filePath, $fileContents);

}

jeyglo
  • 137
  • 1
  • 5