Php 如何使用codeigniter下载xls文件
这里我有一个按钮,如果我点击这个按钮,意味着我想下载一个demo.xls文件,使用php我做过,但现在我想做codeigniter,我试过了,但我不能做?请看我下面的代码Php 如何使用codeigniter下载xls文件,php,codeigniter,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>
<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>
我的模型
使用CodeIgniter下载助手从磁盘下载文件非常简单。阅读手册
最后,在这种情况下,我不会将
downloadFile()
方法放在模型中,而是放在控制器本身。如果您的代码在没有codeigniter(纯php)的情况下工作,只需在codeigniter应用程序中使用相同的代码即可。两者都是php,应该可以工作。
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);
}
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);
}