SlimPHP 应用程序未下载文件

SlimPHP Application not downloading File

我正在尝试使用 Slim 下载文件PHP,但它似乎对我不起作用。

这是我制定的路线:

    $backendApp->post('/export', function ($request, $response, $args) {
        $emails = $this->orginization->exportEmails();
        $exportFile = $this->file->writeEmailExport($emails, 'AllEmails.csv');

        $fh = fopen($exportFile, "r");
        $stream = new \Slim\Http\Stream($fh);

        $response = $response->withHeader('Content-Type', 'application/octet-stream')
            ->withHeader('Content-Description', 'File Transfer')
            ->withHeader('Content-Disposition', 'attachment; filename="' . basename($exportFile) . '"')
            ->withHeader('Content-Length', filesize($exportFile))
            ->withBody($stream);

        return $response;
    });

我知道 $exportFile 是一个有效的 PHP 流媒体资源,因为文件内容会在响应中返回,我只需要为用户触发浏览器文件下载功能。

这些是出现在响应中的 headers:

Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:close
Content-Description:File Transfer
Content-Disposition:attachment; filename="AllEmails.csv"
Content-Length:267
Content-Type:application/octet-stream
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Host:localhost:8080
Pragma:no-cache
X-Powered-By:PHP/5.6.15

有没有什么地方可以立即说明我做错了?我可以在响应选项卡中看到文件的内容返回,所以我知道我正在获取文件的内容,我只需要提示用户下载该文件。

这与您如何调用此代码有关:

$app = new \Slim\App($config);

$app->get("/", function ($request, $response, $args) {

    $response->write(
        <<<EOT
<form method="POST" action="/export">
<input type="submit" value="Download">
</form>
EOT
    );

    return $response;
});

$app->post('/export', function ($request, $response, $args) {
    $exportFile = __DIR__ . '/../test_file.txt';

    $fh = fopen($exportFile, "r");
    $stream = new \Slim\Http\Stream($fh);

    $response = $response->withHeader('Content-Type', 'application/octet-stream')
        ->withHeader('Content-Description', 'File Transfer')
        ->withHeader('Content-Disposition', 'attachment; filename="' . basename($exportFile) . '"')
        ->withHeader('Content-Length', filesize($exportFile))
        ->withBody($stream);

    return $response;
});

您说您可以在回复选项卡中看到信息。这是否意味着您是通过 JavaScript 触发的?如果是这样,那么浏览器会将文件发送回 JS 而不是用户。如果您希望出现文件下载对话框,请提供一个表单(如您所愿 POST),上面有一个按钮供用户单击。