在Yii2中,我需要下载我在/ web / uploads /文件夹中上传的文件。我该怎么做?

时间:2017-07-10 07:17:03

标签: file download upload yii2

以下是视图的一部分,我制作了一个下载按钮。

<h1><?= Html::encode($this->title) ?></h1>

<p>
    <?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
    <?= Html::a('Download', ['download', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
    <?= Html::a('Delete', ['delete', 'id' => $model->id], [
        'class' => 'btn btn-danger',
        'data' => [
            'confirm' => 'Are you sure you want to delete this item?',
            'method' => 'post',
        ],
    ]) ?>

</p>

这是我的控制器上的下载功能,我无法让它工作。

public function actionDownload($id)
    {
        $model = new Items();
        $path = Yii::getAlias('@webroot');
        $file = $path . '/' .$model->item_pathname;
        if (file_exists($file)) {
        Yii::$app->response->sendFile($file);
        }
    }

文件的路径保存在数据库的item_pathname中(例如&#34; /uploads/samplefile.doc"。我不知道如何成功访问它以将其附加到路径变量。为我解决这个问题会有很大的帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

如果下载花费太多时间,我会看到两种可能性

您可以增加脚本的最长执行时间。这不是最好的解决方案,因为脚本仍会因超大文件而超时,但这是最简单的解决方案(可能存在与您的问题无关的性能考虑因素)。为此:

ini_set('max_execution_time', 5*60); // 5 minutes

您可以使用Apache的X-SendFile标头(如果仅在Apache中启用此模块)让Apache处理文件的发送。有关Yii2文档http://www.yiiframework.com/doc-2.0/guide-runtime-responses.html#sending-files的更多相关信息。注意IE中的错误&lt; = 8。

if (file_exists($file)) {
Yii::$app->response->xSendFile($file);
}