如何在CakePHP中下载csv文件

时间:2015-01-22 13:06:40

标签: php file cakephp download

我的webroot / files中有一个csv文件..当我点击链接时我想要下载csv文件。我已经编写了以下代码,该文件也已下载,但该下载文件中没有内容。请帮助下载包含所有内容的csv文件。

这是我的代码:

public function downloadSamplefile()
{
    $name= "abc format.csv";    

    $file_path=HTTP_ROOT."app\webroot\files".$name;
    header('Content-Description: File Transfer');
    header('Content-Type: application/force-download');
    header("Content-Disposition: attachment; filename=\"" . basename($name) . "\";");
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($name));
    $file = @fopen($file_path);
    ob_clean();
    flush();
    readfile(HTTP_ROOT."app\webroot\files".$name); 

    @fclose($file);
    exit;

}

3 个答案:

答案 0 :(得分:1)

如何阅读手册呢? There is a whole page dedicated to how to send files.还有复制和粘贴就绪代码,可以显示如何正确执行此操作。

如果在公共可访问,不受保护的webroot中提供文件,那么将文件推送到php是没有意义的。只需直接链接文件即可。

答案 1 :(得分:0)

我认为问题在于路径(var $file_path)。

IF filesapp\webroot\内的文件夹,那么$ file_path变量将

$file_path=ROOT."app\\webroot\\files\\".$name; // \ is also needed after 'file'
  //double \\ coz of escape char, try with single / also as follows
$file_path=ROOT."app/webroot/files/".$name;
  // best way to use cake php's functionality
$file_path=WWW_ROOT."files".DS.$name;

也改变了readfile和filesize函数参数:

readfile($file_path);
header('Content-Length: ' . filesize($file_path));

删除以下两行作为@ steve的评论:

$file = @fopen($file_path);
@fclose($file);

因为readfile函数本身打开然后自动关闭文件。


如果不能正常工作,请尝试使用:

$name="abc%20format.csv"; //space is encoded as %20 in URLs

答案 2 :(得分:0)

按照以下步骤

<强>步骤1

在你的控制器中创建一个方法

public function downloadSamplefile() {
  $this->viewClass = 'Media';
  // Download app/webroot/files/example.csv
  $params = array(
     'id'        => 'example.csv',
     'name'      => 'example',
     'extension' => 'csv',
     'download'  => true,
     'path'      => APP . 'webroot' . DS. 'files'. DS  // file path
 );
 $this->set($params);
}

<强>步骤-2

转到您的ctp文件&amp;写一个像

的链接
echo $this->Html->link(
'Download Sample',
array(
    'controller' => 'dashboards', // controller name
    'action' => 'downloadSamplefile',  //action name
    'full_base' => true
));

您会在视图文件中看到下载示例链接

当您点击下载示例链接时,将下载一个csv文件,该文件存储在您的app / webroot / files / exampl.csv

参考链接cakephp.org documentation

相关问题