首页 > 解决方案 > 使用 zenframework 3 下载文件

问题描述

我在任何地方都找不到答案,甚至在这里也找不到,所以这是我的问题。

在这个 hello 示例中,控制器下载文件:

class DownloadController extends AbstractActionController 
{
    /**
    * This is the default "index" action of the controller. It displays the 
    * Downloads page.
    */
    public function indexAction() 
    {
        return new ViewModel();
    }

    /**
    * This is the 'file' action that is invoked
    * when a user wants to download the given file.     
    */
    public function fileAction() 
    {


        // Get the file name from GET variable
        $fileName = $this->params()->fromQuery('name', '');

        // Take some precautions to make file name secure
        $fileName = str_replace("/", "", $fileName);  // Remove slashes
        $fileName = str_replace("\\", "", $fileName); // Remove back-slashes

        // Try to open file
        $path = './data/download/' . $fileName;


        if (!is_readable($path)) {
            // Set 404 Not Found status code
            $this->getResponse()->setStatusCode(404);            
            return;
        }

        // Get file size in bytes
        $fileSize = filesize($path);

        // Write HTTP headers
        $response = $this->getResponse();
        $headers = $response->getHeaders();
        $headers->addHeaderLine(
                "Content-type: application/octet-stream");
        $headers->addHeaderLine(
                "Content-Disposition: attachment; filename=\"" . 
                $fileName . "\"");
        $headers->addHeaderLine("Content-length: $fileSize");
        $headers->addHeaderLine("Cache-control: private"); 

        // Write file content        
        $fileContent = file_get_contents($path);
        if($fileContent!=false) {                
            $response->setContent($fileContent);
        } else {        
            // Set 500 Server Error status code
            $this->getResponse()->setStatusCode(500);
            return;
        }

        // Return Response to avoid default view rendering
        return $this->getResponse();

    }
}

在 Apache2 网络服务器中运行它时出现此错误:

A 404 error occurred
Page not found.
The requested controller was unable to dispatch the request.
Controller:
Application\Controller\DownloadController 
No Exception available

但是在使用 PHP 内置服务器时它工作正常:

php -S 0.0.0.0:8081 -t helloworld public/index.php

我在这里做错了什么?

标签: phpdownloadcontrollerzend-framework3

解决方案


我猜你应该返回 $response 而不是 $this->getResponse()。我将展示我用于下载文件的工作代码:

public function downloadAction()
{
    $file = 'file content...';

    $response = $this->getResponse();
    $headers  = $response->getHeaders();
    $headers->addHeaderLine('Content-Type', 'text/csv')
        ->addHeaderLine('Content-Disposition', "attachment; filename=filename.csv")
        ->addHeaderLine("Pragma: no-cache")
        ->addHeaderLine("Content-Transfer-Encoding: UTF-8");

    $response->setContent($file);

    return $response;
}

推荐阅读