如何使用CodeIgniter下载XLS文件



在这里我有一个按钮,如果我单击按钮表示我想下载一个demo.xls文件,使用我做过的php,但是现在我想做codeigniter,我尝试了,但是我不能做吗?请查看我的下面代码

    <button class="btn btn-warning" id="download-btn">
    <i class="fa fa-download" aria-hidden="true"></i>  Download Demo File
</button>

<script type="text/javascript">
$(document).ready(function(){
$("#download-btn").click(function(e){
  e.preventDefault();
     $.ajax({
             type:'POST',
             url :"Staff/downloadDemoFile",
             cache: false,
             contentType: false,
             processData: false,
             success: function(data) {
                 console.log(data);
             },
             error:function(exception){
             alert('Exeption:'+exception);
            }
          });

});
});
</script>

我的控制器

public function downloadDemoFile()
{
    if($this->session->logged_in != TRUE){
        $this->load->view('login');
    }
    else{
    $download= $this->Add_staff_model->downloadFile();
    }
}

我的模型

public function downloadFile()
    { 
            $sFileName = 'demo.xls';
            header("Cache-Control: public");
            header("Content-Description: File Transfer");
            header("Content-Disposition: attachment; filename=$sFileName");
            header("Content-Type: application/zip");
            header("Content-Transfer-Encoding: binary");
            // read the file from disk
            readfile(UPLOAD_PATH_XLS.$sFileName);
    }

使用codeigniter 下载helper 从磁盘下载文件。在此处阅读手册。

public function downloadFile()
{ 
    // load the helper somewhere, i.e in the constructor.
    $this->load->helper('download'); 
    // Use it when necessary
    $sFileName = 'demo.xls'; // filename to be download. With path if necessary: /path/to/demo-xls
    force_download($sFileName, NULL);
 }

作为最终考虑,在这种情况下,我不会将downloadFile()方法放入模型中,而将其放在控制器本身中。