Yii2:如何使用spanjeta / yii2-backup下载备份文件?

时间:2017-07-17 03:49:22

标签: php download yii2 backup

在Yii2项目中,我想下载文件备份。我在操作列中设置了下载按钮。我的代码不起作用,当我点击下载按钮时,它会加载一个空白页面。我需要有人帮我下载文件备份。

my_controller

public function actionDownload($file = null) {
    $this->updateMenuItems();
    if (isset($file)) {
        $sqlFile = $this->path . basename($file);
        if (file_exists($sqlFile)) {
            $request = Yii::$app->getRequest();
            $request->sendFile(basename($sqlFile), file_get_contents($sqlFile));
        }
    }
    throw new HttpException(404, Yii::t('app', 'File not found'));
}

my_view,我正在使用Kartik GridView:

<?php
echo kartik\grid\GridView::widget([
    'id' => 'install-grid',
    'export' => false,
    'dataProvider' => $dataProvider,
    'columns' => array(
        'name',
        'size:ShortSize',
        'create_time',
        //'modified_time:relativeTime',
        [
            'class' => 'kartik\grid\ActionColumn',
            'template' => '{download_action}',
            'header' => 'Download',
            'buttons' => [
                'download_action' => function ($url, $model) {
                    return Html::a('<span class="glyphicon glyphicon-download-alt"></span>', $url, [
                        'title' => Yii::t('app', 'Download Backup'), 'class' => 'download',
                    ]);
                }
            ],
            'urlCreator' => function ($action, $model, $key, $index) {
                if ($action === 'download_action') {
                    $url = Url::to(['backuprestore/download', 'filename' => $model['name']]);
                    return $url;
                }
            }
        ],
    ),
]);
?>

1 个答案:

答案 0 :(得分:1)

我试试,这是有效的。

public function actionDownload($filename = null) {

    $file = $filename;

    $this->updateMenuItems();
    if (isset($file)) {
        $sqlFile = $this->path . basename($file);
        if (file_exists($sqlFile)) {
            Yii::$app->response->sendFile($sqlFile);
        }
        //throw new HttpException(404, Yii::t('app', 'File not found'));
    }
}