如何在codeigniter上的链接上单击下载文本文件

Gee*_*ika 4 php csv codeigniter

我有文本文件包含CSV文件格式的样本,我希望我的用户可以在链接点击下载该文件.

此文件位于此文件夹结构中:

资产 - > csv->采样CSV-Format.txt

这是我尝试过的代码:

<?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>
Run Code Online (Sandbox Code Playgroud)

此代码在页面加载时下载文件而不是链接单击.此外,它正在下载页面的整个html结构我只想要文本文件中我写的文本.

请指导问题在哪里?

Sop*_*loy 6

您可以通过HTML5下载atrribute简单地完成此操作.只需在下载链接中添加此行即可.

<a href="<?php echo base_url();?>assets/csv/Sample-CSV-Format.txt" download="Sample-CSV-Format.txt"> HERE </a>
Run Code Online (Sandbox Code Playgroud)


Car*_*dev 2

您可以这样做,它不会重定向您并且也适用于较大的文件。

在你的控制器“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();
        }
}
Run Code Online (Sandbox Code Playgroud)

在你的视图“view.php”中

<a href="<?=base_url("Controller/downloadFile")?>">Download</a>
Run Code Online (Sandbox Code Playgroud)