如何在zendframework2中设置正确的文件下载路径



我的控制器:

public function downloadAction()
    {
        $param['filename'] = $this->params()->fromRoute('filename');
$param['foldername'] = $this->params()->fromRoute('foldername');
    $fileName = $param['filename']; //bala.pdf
    $folderName = $param['foldername'];  //j1005
$fileContents = file_get_contents($fileName);
$response = $this->getResponse();
$response->setContent($fileContents);
$headers = $response->getHeaders();
$headers->clearHeaders()
    ->addHeaderLine('Content-Type', 'application/pdf')
    ->addHeaderLine('Content-Disposition', 'attachment; filename="' .$fileName . '"')
    ->addHeaderLine('Content-Length', strlen($fileContents));

return $this->response;
}

我的文件位置是/data/basepaper/j1005/bala.pdf,但我不知道如何设置下载文件

的路径

正确分配变量(例如,在使用前初始化空数组)和使用变量(数组仅用于再次分配变量…)可能会很好。

关于当前的问题,您需要了解ZF2上文件管理的基本内容,因此请阅读index.php:

<?php
    /**
     * This makes our life easier when dealing with paths. Everything is relative
     * to the application root now.
     */
    chdir(dirname(__DIR__));

这意味着您可以引用项目根目录中的任何文件。

所以你的代码变成:

public function downloadAction()
{
    // Combine assignation (unused array, and non initialised...)
    $fileName = $this->params()->fromRoute('filename');
    $folderName = $this->params()->fromRoute('foldername');
    $fileContents = file_get_contents("data/basepaper/{$folderName}/{$fileName}");
    $response = $this->getResponse();
    $response->setContent($fileContents);
    $headers = $response->getHeaders();
    $headers->clearHeaders()
            ->addHeaderLine('Content-Type', 'application/pdf')
            ->addHeaderLine('Content-Disposition', 'attachment; filename="' .$fileName . '"')
            ->addHeaderLine('Content-Length', strlen($fileContents));
    return $this->response;
}

最新更新