如何在CakePHP中下载CSV文件
我的webroot / files中有一个csv文件。每当我单击链接时,我都希望下载该csv文件。我已经编写了以下代码,该文件也正在下载,但该下载文件中没有内容。因此,请帮助下载所有内容的csv文件。
I have a csv file in my webroot/files..when ever I click on a link I want that csv file to be downloaded. I have written the following code and the file is also getting downloaded but there is no content in that downloaded file.so please help to get download the csv file with all content.
这是我的代码:
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;
}
问题是在路径中(var $ file_path
)。
Problem is in path(var $file_path
) I think.
IF 文件
是 app\webroot\
内的文件夹,则$ file_path变量将为
IF files
is a folder inside app\webroot\
then $file_path variable will be
$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;
然后更改读取文件并文件大小函数参数还:
And change readfile and filesize function parameter also:
readfile($file_path);
header('Content-Length: ' . filesize($file_path));
删除,以下两行为@steve的注释:
Remove following two line as @steve's comment:
$file = @fopen($file_path);
@fclose($file);
因为读取文件本身会自动打开,然后自动关闭文件。
Because readfile function itself OPEN then CLOSE the file automatically.
如果不起作用,请尝试以下操作:
$name="abc%20format.csv"; //space is encoded as %20 in URLs