php – 如何在codeigniter上的链接上单击下载文本文件
发布时间:2020-12-13 17:49:04 所属栏目:PHP教程 来源:网络整理
导读:我有文本文件包含CSV文件格式的样本,我希望我的用户可以在链接点击下载该文件. 此文件位于此文件夹结构中: assets-csv-Sample-CSV-Format.txt 这是我尝试过的代码: ?php $file_name = "Sample-CSV-Format.txt"; // extracting the extension: $ext = subst
我有文本文件包含CSV文件格式的样本,我希望我的用户可以在链接点击下载该文件.
此文件位于此文件夹结构中:
这是我尝试过的代码: <?php $file_name = "Sample-CSV-Format.txt"; // extracting the extension: $ext = substr($file_name,strpos($file_name,'.') + 1); header('Content-disposition: attachment; filename=' . $file_name); if (strtolower($ext) == "txt") { // works for txt only header('Content-type: text/plain'); } else { // works for all header('Content-type: application/' . $ext);extensions except txt } readfile($decrypted_file_path); ?> <p class="text-center">Download the Sample file <a href="<?php echo base_url();?>assets/csv/Sample-CSV-Format.txt">HERE</a> It has a sample of one entry</p> 此代码在页面加载时下载文件而不是链接单击.此外,它正在下载页面的整个html结构我只想要文本文件中我写的文本. 请指导问题在哪里? 解决方法
你可以这样做,它不会重定向你,也适用于较大的文件.
在你的控制器“Controller.php” function downloadFile(){ $yourFile = "Sample-CSV-Format.txt"; $file = @fopen($yourFile,"rb"); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=TheNameYouWant.txt'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($yourFile)); while (!feof($file)) { print(@fread($file,1024 * 8)); ob_flush(); flush(); } } 在你的视图“view.php” <a href="<?=base_url("Controller/downloadFile")?>">Download</a> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |