如何编写上传图像的代码并将图像保存在数据库和Yii 2中的所选文件夹中

时间:2015-06-01 04:57:51

标签: php yii2

请任何人简要解释代码的放置位置。并提供一个示例代码以将图像保存在数据库和所选文件夹中

我在模型中使用此代码

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

请帮我解决这个问题。

感谢。

3 个答案:

答案 0 :(得分:0)

要将上传的图像保存在选定的文件夹中:(请记住,两个示例中的$ image都是UploadForm实例https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md

    $image->file = UploadedFile::getInstance( $image, 'file' );

    if ($image->file && $image->validate())
    {
    $tmp = '/anyfolder/' . array_pop( explode( '/', $image->file->tempName ) );
    $user->image = $tmp;
    $user->save();
    $image->file->saveAs( Yii::getAlias( '@webroot' ) . $tmp . '.' . $image->file->extension );

    }

tempName可帮助您使用系统指定的唯一名称保存图像。上面的代码还保存了图像中$ image的关系路径(保存地址的字符串)$ user。

现在将上传的图像保存为数据库中的blob:

    $image->file = UploadedFile::getInstance( $image, 'file' );

    if ($image->file)
    {
    $user->image_blob = file_get_contents( $image->file->tempName );
    $user->save();

    }

答案 1 :(得分:0)

This is your controller code:

$fileupload = UploadedFile::getInstance($model, 'file');
          if(!empty($fileupload)){
              $fileupload->saveAs('uploads/' . $fileupload->baseName . '.' . $fileupload->extension);
              $model->file = $fileupload->baseName . '.' . $fileupload->extension;
              $model->save();
          }
For this code to work: your database field name should be file. And the image saved will go to the the folder uploads located inside the web directory.

In model:
public function rules()
    {
        return [
            //other rules
            [['file'], 'safe']
        ];
    }

Note: Do not make the file required in rules.

In your view:

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

    <?= $form->field($model, 'file')->fileInput() ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

        <?php ActiveForm::end(); ?>

答案 2 :(得分:0)

使用此代码:此代码将您的图像上传到文件夹上传但不上传到数据库中。使用此代码编辑您的。

这是控制器代码。

public function actionCreate()
  {
      $model = new Your_model();

      if ($model->load(Yii::$app->request->post())) {

          $fileupload = UploadedFile::getInstance($model, 'file');
          if(!empty($fileupload)){
              $fileupload->saveAs('uploads/' . $fileupload->baseName . '.' . $fileupload->extension);
          }

          return $this->redirect(['index']);
      } else {
          return $this->render('create', [
              'model' => $model,
          ]);
      }
  }

在模型中,您只需要为图像提供规则。

[['file'], 'safe']

注意:请勿声明&#39; file&#39;在必要的规则。

在您看来:

<div class="product-form">

        <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

         <?= $form->field($model, 'file')->fileInput() ?>

        <div class="form-group">
            <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
        </div>

        <?php ActiveForm::end(); ?>

    </div>

我已经编辑了一下我的代码。试试这个并告诉我是否有错误。不要忘记为uploads文件夹提供读写权限。

希望这会奏效。