【问题标题】:how to add uploded file name in to database using yii如何使用 yii 将上传的文件名添加到数据库中
【发布时间】:2021-05-26 12:00:00
【问题描述】:

我想用 yii 上传文件,我做到了。当我点击提交按钮时,文件将保存在它应该在的文件夹中。但是,我也想将文件名添加到数据库中。我怎样才能做到这一点?

这是我的控制器:

public function actionUpload()
{
  $model = new TourImage();
  if (Yii::$app->request->isPost) {
    $model->imageFile = UploadedFile::getInstance($model, ‘imageFile’);
    if ($model->upload()) {
      // file is uploaded successfully
      return;
    }
  }
  return $this->render(‘upload’, [
  ‘model’ => $model
  ]);
  
}

【问题讨论】:

    标签: php activerecord yii yii2


    【解决方案1】:

    您可以从 UploadedFile.getInstance() 中提取原始文件的名称并将其分配给您的模型的属性(这通常在您的模型“TourImage”中完成,在上传方法中您必须实施)。

    因此,如果您的控制器操作中有此内容:

    $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
    

    然后,在 TourImage 模型的 upload() 方法中:

    $this->your_model_attribute = $this->imageFile->name; // The original name of the file being uploaded
    

    your_model_attributes 更改为要保存文件名的模型的属性。

    查看 UploadedFile 对象的公共属性: https://www.yiiframework.com/doc/api/2.0/yii-web-uploadedfile

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2020-12-10
      • 2013-08-15
      • 1970-01-01
      • 2020-06-06
      • 2015-06-28
      • 1970-01-01
      相关资源
      最近更新 更多