Yii 2本地上传和保存图像文件,图像URL保存在DB中

时间:2015-02-10 05:59:05

标签: php image upload yii2

我在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的文件上传演示中,没有涉及或显示的控制器。

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

修改

关于@ 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
            }
        }
    }

4 个答案:

答案 0 :(得分:1)

在模型中使用以下后遗症

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
        }
    }
}

用您自己的属性替换上述徽标。即。图像

答案 1 :(得分:0)

尝试以下 -

在您的控制器

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

您的图片将作为&#34; $ path保存在服务器上。日期(&#39; Y&#39;)&#39; /&#39; .date(&#39; M&#39)。&#39; /&#39; .date(&#39; d&#39;)。&#39; /&#39;。$ this-&gt; image-&gt; baseName。 &#39;&#39; 。 $这 - &GT;图像 - &GT;延伸&#34 ;. 在数据库中,它将保存为&#34;日期(&#39; Y&#39;)。&#39; /&#39;。日期(&#39; m&#39;)。&#39 ; /&#39;。日期(&#39; d&#39;)。&#39; /&#39;。$ this-&gt; image-&gt; baseName。 &#39;&#39; 。 $这 - &GT;图像 - &GT;延伸&#34;

答案 2 :(得分:0)

表格

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

答案 3 :(得分:0)

  

尝试一下

     

MediaHelper::saveMultipleFiles($_FILES['EmpDocumentForm'],'emp_document/');

public static function saveMultipleFiles($img_obj,$path){

        $upload_path =  Yii::getAlias('@backend')."/web/uploads/$path/";
        if(!file_exists($upload_path)) {
            FileHelper::createDirectory($upload_path, $mode = 0777, $recursive = true);
        }

        $arr_size = sizeof($img_obj['name']['input_img']);

        if(!empty($img_obj['name']['input_img'][0])){

            for($i=0; $i<$arr_size; $i++){
                $ex = pathinfo($img_obj['name']['input_img'][$i]);
                $extension = $ex['extension'];
                $new_name = str_replace(' ', '_', $ex['filename']). '_' . time() . '.' . $extension;
                $new_path = Yii::getAlias('@backend') . "/web/uploads/" . $path;
                $file_name = $img_obj['name']['input_img'][$i];
                $tmp_name = $img_obj['tmp_name']['input_img'][$i];

                if(move_uploaded_file($tmp_name,$new_path.$new_name)) {
                    $media_id = self::saveFile($new_name,$new_path,$path,$file_name);
                    if($media_id){
                        return $media_id;
                    } else {
                        return false;
                    }
                }else{
                    return false;
                }
            }
        } else {
            return false;
        }
    }



public static function saveFile($new_name,$new_path,$path,$file_name){
    $media = new Media();
    $media->file_name = $new_name;
    $media->file_path = $new_path . $media->file_name;
    $media->original_name = $file_name;
    $media->file_url = Yii::$app->urlManager->createAbsoluteUrl("/web/uploads/".$path.$media->file_name);       
    if($media->save()){
        return $media->id;
    } else {
        return false;
    }
}