简体   繁体   English

Yii2-如何在数据库中上传和存储图像

[英]Yii2 - How to upload & store Images in Database

I am using yii2 . 我正在使用yii2 I am trying to select a file and then want to save it to my database table. 我正在尝试选择一个文件,然后将其保存到我的数据库表中。 I am using core PHP for it. 我正在使用core PHP Below is my code 下面是我的代码

<form action = <?=\yii\helpers\Url::toRoute(['meteracceptanceheader/import'])?> method ="post"
           enctype="multipart/form-data">
.
.
.
.
.
.
.

<div class="row">
                <div class="col-md-2">

                    Upload-Image
                    <input type="file" name="file"/>
                    <br />
                    <input type="submit" class="btn btn-primary pull-left"  />
                </div>
            </div>
</form>

Controller 调节器

public function actionImport()
{

    .
    .
    . // my other code

    $file = $_FILES['file'];
    $fileName = $_FILES['file']['name'];
    $fileExt = explode('.',$fileName);
    print_r($file);
    die();
    .
    .
    .
    .

return $this->render('excel_finish', ['records_saved' => $ok_count,'status_arr'=>$status_arr]);
}

Database Table 数据库表

在此处输入图片说明

In the above table, id is auto-increment accpt_id is the model id which I already have and file_path is the name of the file which should be saved like 123.jpg . 在上表中, id是自动递增的accpt_id是我已经拥有的model id ,而file_path是应该保存的文件名,如123.jpg

The file should be saved into a folder uploads/meter_acceptance/ and append with the file name. 该文件应保存到uploads/meter_acceptance/文件夹中,并附加文件名。

Note: 注意:

I have already know how to upload images via the active form but here I want to do it in a traditional way. 我已经知道如何通过活动表格上传图像,但是在这里我想以传统方式进行。

Any help would be highly appreciated. 任何帮助将不胜感激。

your controller should be like this 您的控制器应该是这样的

public function actionUpload(){

    $model = new Images();
    $uploadPath = Yii::getAlias('@root') .'/uploads/';

    if (isset($_FILES['image'])) {
        $file = \yii\web\UploadedFile::getInstanceByName('image');
      $original_name = $file->baseName;  
      $newFileName = \Yii::$app->security
                        ->generateRandomString().'.'.$file->extension;
       // you can write save code here before uploading.
        if ($file->saveAs($uploadPath . '/' . $newFileName)) {
            $model->image = $newFileName;
            $model->original_name = $original_name;
            if($model->save(false)){
                echo \yii\helpers\Json::encode($file);
            }
            else{
                echo \yii\helpers\Json::encode($model->getErrors());
            }

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

    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM