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:
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"
Author by
Admin
Updated on June 29, 2022Comments
-
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 about 7 yearsplease always check if
$download
is not empty before using it. It is not dangerous here, but it could be somewhere else. -
Bhavin Thummar almost 5 yearsCan we update the file name which will be downloaded without change original file name?
-
Bhavin Thummar almost 5 years@vishuB Thank you. It's working as per requirement.