Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Download in Yii2

public function actionUnduh($id) {
        $download = PstkIdentifikasi::findOne($id);
        $path = Yii::getAlias('../web/bukti/') . $download->bukti;

        if (file_exists($path)) {
            //return \Yii::$app->response->sendFile($download->pre_paper,@file_get_contents($path));
            return Yii::$app->response->sendFile($path);
        }
    }  

I need to download file from folder web/bukti, the code not error but the code doesn't work, Anyone can help me :(

like image 634
christ Avatar asked Aug 03 '16 03:08

christ


2 Answers

public function actionUnduh($id) 
{ 
    $download = PstkIdentifikasi::findOne($id); 
    $path = Yii::getAlias('@webroot').'/bukti/'.$download->bukti;

    if (file_exists($path)) {
        return Yii::$app->response->sendFile($path, 'File name here');
    }
}

Refer below:

Yii2 Aliases

Yii2 sendFile()

like image 116
vishuB Avatar answered Dec 25 '22 11:12

vishuB


Firstly you can write an action in SiteController.php like this:

public function actionDownload()
{
    $file=Yii::$app->request->get('file');
    $path=Yii::$app->request->get('path');
    $root=Yii::getAlias('@webroot').$path.$file;
    if (file_exists($root)) {
        return Yii::$app->response->sendFile($root);
    } else {
        throw new \yii\web\NotFoundHttpException("{$file} is not found!");
    }
}

then you can call this function anywhere:

Yii::$app->urlManager->createUrl(['site/download','path'=>'/upload/files/','file'=>'filename.pdf'])

Be careful your files must be in this directory:

"backend/web/upload/files/filename.pdf"

or

"frontend/web/upload/files/filename.pdf"

like image 36
Mahmut Aydın Avatar answered Dec 25 '22 12:12

Mahmut Aydın