Yii2 sendFile() - 尝试获取非对象的属性


Yii2 sendFile() - Trying to get property of non-object

嘿伙计们,我正在尝试设置一个下载按钮,用户可以在其中下载文件,该文件是使用 kartik 的文件输入小部件(单次上传)上传的。

代码驻留在 CRUD 生成的视图/控制器/模型中。

这是视图按钮代码,

        <?= Html::a('Download Uploaded File', ['download', 'id' => $model->form_id], [
    'class' => 'btn btn-danger',
    'data' => [
        'confirm' => 'Are you sure you want to download this item?',
        'method' => 'post',
    ],
]) ?>

控制器功能(下载),

public function actionDownload($id) {
    $model = $this->findModel($id);
   $path = Yii::getAlias('@web') . '/uploads';
   $file = '/borang/'.$model->form_id.'.'.$model->file->extension;
   if (file_exists($file)) {
   Yii::$app->response->sendFile($file);
  }
}

控制器功能(在创建操作内上传)

public function actionCreate()
    {   
        $model = new FormMovement();
        if ($model->load(Yii::$app->request->post())) {
            $model->file = UploadedFile::getInstance($model, 'file');
            if (!empty($model->file) && $model->validate()) {
                    $model->fm_upload = 'uploads/borang/'.$model->form_id.'.'.$model->file->extension;
                    $model->save();
                    $model->file->saveAs('uploads/borang/'.$model->form_id.'.'.$model->file->extension);
                    return $this->redirect(['view', 'id' => $model->form_id]);
            }else{
                $model->save();
                return $this->redirect(['view', 'id' => $model->form_id]);
            }
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

这是错误日志,C:''xampp''htdocs''adminsys''frontend''controllers''FormMovementController.php:181 中的"试图获取非对象的属性"

它指向,

$file = '/borang/'.$model->form_id.'.'.$model->file->extension;

在下载操作(控制器)中

试试这个方式:

public function actionDownload($id) {
    $model = $this->findModel($id);
    $path = Yii::getAlias('@web') . '/uploads';
    $ext = substr(strrchr($model->file,'.'),1);
    $file = $path.$model->file;
    $download = '/borang/'.$model->form_id.'.'.$ext;
    if(file_exists($file)) 
       Yii::$app->response->sendFile($download);
}

strrchr()

问题出在您的下载功能中。您没有在模型中保存扩展。有很多方法可以获取文件的扩展名。

public function actionDownload($id) {
    $model = $this->findModel($id);
   $path = Yii::getAlias('@webroot') . '/uploads';
   $fileextension=end(explode('.',$model->fm_upload));
   $file = $path.'/borang/'.$model->form_id.'.'.$fileextension;
   if (file_exists($file)) {
   Yii::$app->response->sendFile($file);
  }
}
您需要

确保在服务器上启用了set_time_limit 才能使下载选项正常工作,因为默认情况下它将在服务器上禁用。