In a Yii2 project I want to download file backup. I have setup the download button in my action column. My code doesn't work, when I click the download button, it load a blank page. I need someone to help me to download the file backup.
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
, I'm using 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;
}
}
],
),
]);
?>
I try,It's work.
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'));
}
}