功能下载在Yii2中

chr*_*ist 2 file download 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);
        }
    }  
Run Code Online (Sandbox Code Playgroud)

我需要从文件夹web/bukti下载文件,代码没有错误,但代码不起作用,任何人都可以帮助我:(

vis*_*huB 10

请参阅Yii2别名

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');
    }
}
Run Code Online (Sandbox Code Playgroud)


Mah*_*dın 5

首先,您可以在 SiteController.php 中编写一个操作,如下所示:

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!");
    }
}
Run Code Online (Sandbox Code Playgroud)

那么你可以在任何地方调用这个函数:

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

请注意,您的文件必须位于此目录中:

“后端/网络/上传/文件/文件名.pdf”

或者

“前端/网络/上传/文件/文件名.pdf”