2016-06-14 70 views
0

我目前正在使用Zend Framework的PHP项目。我在控制器中创建一个没有任何问题的CSV文件,但是希望用户能够通过单击视图中的按钮来下载文件。从PHP项目的tmp文件夹下载CSV

在我.phtml我:

<a class="btn" href="<?php echo $this->download;?>" download>Export to CSV</a> 

$this->download在控制器被设置:

$view["download"] = $this->_createCSV($bqc_jobs, $startDate, $endDate, $processor_id, $defaultTime); 

_createCSV函数创建CSV并将其存储在该网站所使用的临时目录。然后它返回文件路径。

private function _createCSV($jobs, $start, $end, $user=null, $minutes){ 
    $format = "Ymd_His"; 
    if(!$start && !$user){ 
     $start = date($format, strtoTime("-" . $minutes . " minutes")); 
    } 

    if(!$end){ 
     $end = \DateTime::createFromFormat($format, date($format))->format($format); 
    } 
    $directory = Config::$tempDir; 
    $fileName = $directory . "/" . ($user ? $user . "_" : "") . ($start ? $start . "_" : "") . $end . "_report.csv"; 

    $file = fopen($fileName, 'w'); 
    foreach ($jobs as $job){ 
     fputcsv($file, $job); 
    } 

    fclose($file); 

    return $fileName; 
} 

单击按钮时,浏览器会尝试下载文件,但由于找不到文件而导致错误。这是有道理的,因为浏览器不应该访问临时文件夹,但我不完全确定如何解决这个问题。

+2

在Laravel我最近通过Streaming一个文件达到了同样的效果 - 我做了一个快速的谷歌,遇到了这可能有助于(不熟悉zend)http://www.sasaprolic.com/2013/02/sending-stream- response-with-zend.html – Djave

+0

@Djave看起来很有前途,谢谢 –

回答

1

如果您无法看到该文件夹​​,由于UNIX文件权限,那么你唯一的选择将是:

  1. 变化tmp的文件夹中的文件权限,以便您的Web服务器可以读/写使用chmod/chown(我假设它是一个linux系统?)
  2. 使用具有足够权限的其他文件夹
  3. 不要将文件存储在磁盘上 - 将其存储在数据库中(而不是最佳)。

一旦你确定你的文件权限是为了和该文件可以被Apache,it appears that you should be able阅读使用PHP的readfile功能实际传输文件返回给浏览器:

<?php 
$file = '/tmp/monkey.gif'; 

if (file_exists($file)) { 
    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename="'.basename($file).'"'); 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate'); 
    header('Pragma: public'); 
    header('Content-Length: ' . filesize($file)); 
    readfile($file); 
    exit; 
} 
?> 
+1

我不认为这是文件权限问题,而是'tmp'目录不是随时在网站上托管。 –

+0

那么您正在寻找的是一种打开临时文件并提供它的方式,但它实际上并不属于Web服务器配置文件中网站范围的一部分?你使用什么网络服务器? –

+0

是的,非常。我有权访问服务器端的文件,但我希望它可以在客户端上下载,所以我需要弄清楚如何将它传递给客户端。我正在使用Apache –