doumen5491 2016-01-21 05:03
浏览 241
已采纳

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

Hey guys I am trying to set a download button where a user can download a file, which is uploaded using kartik's File Input Widget(single upload).

The codes resides inside the CRUD generated view/controllers/models.

This is the view button code,

        <?= 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',
    ],
]) ?>

Controller function(Download),

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

  }
}

Controller function(Upload which is inside the create action)

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,
            ]);
        }
    }

This is the error log, 'Trying to get property of non-object' in C:\xampp\htdocs\adminsys\frontend\controllers\FormMovementController.php:181

which points to,

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

inside the Download action(controller)

  • 写回答

3条回答 默认 最新

  • douqiao5543 2016-01-21 05:33
    关注

    Try this way:

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探