如何使用codeigniter下载xls文件

时间:2017-05-01 16:43:33

标签: php codeigniter

这里我有一个按钮,如果我点击按钮意味着我想下载一个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);

    }

1 个答案:

答案 0 :(得分:0)

使用CodeIgniter Download Helper 从磁盘下载文件非常简单。阅读手册here

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()方法放在模型中,而是放在控制器本身中。