Function Download in Yii2

13,360

Solution 1

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()

Solution 2

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"

Share:
13,360
Admin
Author by

Admin

Updated on June 29, 2022

Comments

  • Admin
    Admin almost 2 years
    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 :(

  • Francis Ngueukam
    Francis Ngueukam about 7 years
    please always check if $download is not empty before using it. It is not dangerous here, but it could be somewhere else.
  • Bhavin Thummar
    Bhavin Thummar almost 5 years
    Can we update the file name which will be downloaded without change original file name?
  • Bhavin Thummar
    Bhavin Thummar almost 5 years
    @vishuB Thank you. It's working as per requirement.