【问题标题】:Yii 2 Upload and Save Image Files Locally and Image URL is Saved in DBYii 2 在本地上传和保存图像文件,图像 URL 保存在数据库中
【发布时间】:2015-02-10 05:59:05
【问题描述】:

我在 Yii 2 中遵循了不同的文件/图像上传实现。其中之一来自 Kartik 的小部件,位于:http://demos.krajee.com/widget-details/fileinput

在我的观点中,_form.php

<div class="col-sm-8">
   <?php
      // A block file picker button with custom icon and label
      echo FileInput::widget([
                    'model' => $model,
                    'attribute' => 'image',
                    'options' => ['multiple' => true],
                    'pluginOptions' => [
                        'showCaption' => false,
                        'showRemove' => false,
                        'showUpload' => false,
                        'browseClass' => 'btn btn-primary btn-block',
                        'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
                        'browseLabel' =>  'Upload Receipt'
                    ],
                    'options' => ['accept' => 'image/*']
                ]);
   ?>
</div>

我只向您展示了我的一部分观点。该图像上传块伴随着其他字段,如客户姓名、日期和至、产品名称等和提交按钮。

我也已经生成了模型和控制器。

我的控制器的一部分是这样的:

   public function actionCreate()
   {
      $model = new Invoice();
      if ($model->load(Yii::$app->request->post()) && $model->save()) {
         return $this->redirect(['view', 'id' => $model->inv_id]);
      } 
      else {
         return $this->render('create', [
             'model' => $model,
         ]);
      }
   }

我还没有在我的 actionCreate 中添加任何东西,因为我仍然没有任何想法。而且在 Kartik 的文件上传演示中,没有涉及或显示任何控制器。

如何将我选择上传的图片的 URL/路径保存在我的数据库中,并在本地保存该图片?

编辑:

关于@arogachev 的回答,这是我的 afterSave 在我的模型中的样子,但图像路径仍然没有保存在我的数据库中:

    public function afterSave($insert, $changedAttributes)
    {
        if(isset($this->image)){
            $this->image = UploadedFile::getInstance($this,'image');
        if(is_object($this->image)){
            $name = Yii::$app->basePath . 'C:\wamp3\www\basicaccounting\web\uploads';  //set directory path to save image
            $this->image->saveAs($name.$this->inv_id."_".$this->image);   
            $this->image = $this->inv_id."_".$this->image;    //appending id to image name            
        Yii::$app->db->createCommand()
                  ->update('invoice', ['image' => $this->image], 'inv_id = "'.$this->inv_id.'"')
                  ->execute(); //manually update image name to db
            }
        }
    }

【问题讨论】:

  • 你误解了我的变量 $name 它只是我们存储 img 的文件夹的路径。编辑了我的答案。打印每个变量的输出,看看你在哪里出错了。

标签: php image upload yii2


【解决方案1】:

在你的模型中使用下面的 aftersave

public function afterSave($insert, $changedAttributes)
{
    if(isset($this->logo)){
        $this->logo=UploadedFile::getInstance($this,'logo');
    if(is_object($this->logo)){
        $path=Yii::$app->basePath . '/images/';  //set directory path to save image
        $this->logo->saveAs($path.$this->id."_".$this->logo);   //saving img in folder
        $this->logo = $this->id."_".$this->logo;    //appending id to image name            
    \Yii::$app->db->createCommand()
              ->update('organization', ['logo' => $this->logo], 'id = "'.$this->id.'"')
              ->execute(); //manually update image name to db
        }
    }
}

用你自己的属性替换上面的标志。 IE。图片

【讨论】:

  • 嗨。谢谢你,但它不起作用。我编辑了我的问题,我将 afterSave 放在我的模型中。
  • 为什么要将图片的全路径保存到db?保存图像名称就足够了.. 如果您保存完整路径,那么在将其上传到服务器时会让您头疼。
【解决方案2】:

试试下面给出的 -

在你的控制器中

if($model->image = UploadedFile::getInstance($model, 'image'))
{
    if ($model->upload())
    {
    // file is uploaded successfully
    }
}    

在你的模型中

public function upload()
{
    $path = \Yii::$app->params['basepath'];
    if (!is_dir($path)) {
    $image_path = BaseFileHelper::createDirectory($path,0777,true);
    }
    $this->image->saveAs($path . date('Y').'/'.date('m').'/'.date('d').'/'.$this->image->baseName . '.' . $this->image->extension);
    $this->image = date('Y').'/'.date('m').'/'.date('d').'/'.$this->image->baseName . '.' . $this->image->extension; // Assign image path to store in Database column (image).
    return true;
}

您的图像将在服务器上保存为 "$path .date('Y').'/'.date('m').'/'.date('d').'/'.$this ->图像->baseName . '.' . $this->image->extension”。 并在数据库中保存为 "date('Y').'/'.date('m').'/'.date('d').'/'.$this->image-> baseName . '.' . $this->image->extension".

【讨论】:

    【解决方案3】:

    形式

    <?= $form->field($model, 'images[]')->widget(FileInput::classname(), [
           'options' => ['accept' => 'image/*', 'multiple' => true],
           'pluginOptions' => [
               'previewFileType' => 'image',
               'allowedFileExtensions' => ['jpg', 'gif', 'png', 'bmp','jpeg'],
               'showUpload' => true,
    
               'overwriteInitial' => true,
    
           ],
       ]);
    ?>
    

    在模型中

    public $images;
     public function rules()
    {
        return [
            [['name', 'price'], 'required'],
            [['price'], 'integer'],
            [['images'],'file', 'maxFiles' => 4],
            [['name'], 'string', 'max' => 100],
        ];
    }
    

    在控制器中

    public function actionCreate()
    {
        $model = new Product();
             if ($model->load(Yii::$app->request->post())) {
                $model->save();
    
                    $file = UploadedFile::getInstances($model, 'images');
                           foreach ($file as $file) {
                            $path =Yii::getAlias('@frontend').'/uploads/'.$file->name;
                              $file->saveAs($path);
    
                }
    
            return $this->redirect(['view', 'id' => $model->id]);
        }
    
        return $this->render('create', [
            'model' => $model,
        ]);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-20
      • 2014-08-09
      • 2014-12-11
      • 1970-01-01
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 2017-09-25
      • 2012-05-21
      相关资源
      最近更新 更多