本文介绍了图像保存在文件夹中,但未保存在 yii2.0 中的数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 yii 的新手,我曾经在数据库中上传图像,但图像存储在文件夹中但未保存在数据库中,此代码有什么问题无法解决

 公共函数 actionCreate(){$model = 新工作;//$site_url=Yii::$app->getUrlManager()->createAbsoluteUrl('');if ($model->load(Yii::$app->request->post()) && $model->save()) {$image = UploadedFile::getInstance($model,'image');$imagepath='上传/工作/';$path=$imagepath.rand(10,100).$image->name;如果(!空($图像)){$image->saveAs($path);$model->image=$image->name;$model->save();}返回 $this->redirect(['view', 'id' => $model->id]);}别的 {//echo "文件未加载";}返回 $this->render('create', ['模型' =>$模型,]);}

模型在这里被命名为 Jobs.php.

namespace app\models;使用 Yii;使用 yii\web\UploadedFile;使用 yii\base\Model;/*** 这是表jobs"的模型类.** @property 整数 $id* @property 整数 $users_id* @property 字符串 $title* @property 字符串 $deadline* @property 字符串 $urgency*/作业类扩展 \yii\db\ActiveRecord{/*** @inheritdoc***/公共 $image;公共静态函数 tableName(){返回工作";}/*** @inheritdoc*/公共函数规则(){返回 [[['users_id', 'title', 'deadline', 'urgency'], 'required'],[['users_id'], '整数'],[['内容'],'字符串'],[['截止日期'],'必需'],[['紧急'],'字符串'],[['紧急'],'安全'],[['图像'],'文件','skipOnEmpty'=>true,'extensions'=>'png,gif,jpg'],[['title'], 'string', 'max' =>[255]];}/*** @inheritdoc*/公共函数attributeLabels(){返回 ['id' =>Yii::t('app', 'ID'),'users_id' =>Yii::t('app', '用户名'),'content'=> Yii::t('app','Content'),'标题' =>Yii::t('app', 'Title'),'截止日期' =>Yii::t('app', '截止日期'),'紧急' =>Yii::t('app', '紧急'),'图像' =>Yii::t('app', '图片'),];}}

这里的视图文件被命名为 (_form.php)

use yii\helpers\Html;使用 yii\widgets\ActiveForm;使用 yii\web\UploadedFile;//使用kartik\widgets\FileInput;/* @var $this yii\web\View *//* @var $model app\models\Jobs *//* @var $form yii\widgets\ActiveForm */?><div class="jobs-form"><?php$form = ActiveForm::begin(['选项' =>['enctype' =>'多部分/表单数据']]);?><?= $form->field($model, 'users_id')->textInput() ?><?= $form->field($model, 'content')->textInput(['maxlength' => true]) ?><?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?><?= $form->field($model, 'deadline')->textInput() ?><?= $form->field($model, 'urgency')->dropDownList([ 'No', 'yes', ], ['prompt' => '']) ?><?= $form->field($model, 'image')->fileInput() ?><div class="form-group"><?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

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

在此处输入代码

请帮我将图片上传到数据库中,我不知道这段代码有什么问题.

解决方案

更改您的上传代码,如下所示:

 if ($model->load(Yii::$app->request->post()) && $model->save()) {$image = UploadedFile::getInstance($model,'image');$imagepath='上传/工作/';$rand_name=rand(10,100);如果($图像){$model->image = "category_{$rand_name}-{$image}";}if($model->save()):如果($图像):$image->saveAs($imagepath.$model->image);万一;万一;返回 $this->redirect(['view', 'id' => $model->id]);}

i am new in yii and i use to upload images in databse but images are stored in folder but not saved in database what is the problem with this code coud not undurstand

   public function actionCreate()
    {

        $model = new Jobs;


    //  $site_url=Yii::$app->getUrlManager()->createAbsoluteUrl('');

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

            $image = UploadedFile::getInstance($model,'image');

            $imagepath='upload/jobs/';

            $path=$imagepath.rand(10,100).$image->name;

            if(!empty($image)){
                $image->saveAs($path);
                $model->image=$image->name;
                $model->save();
            }               
                return $this->redirect(['view', 'id' => $model->id]);
            }                       
        else {

           // echo "file not ulpoaded";
        }

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

model is here named as Jobs.php.

namespace app\models;

use Yii;
use yii\web\UploadedFile;
use yii\base\Model;

/**
 * This is the model class for table "jobs".
 *
 * @property integer $id
 * @property integer $users_id
 * @property string $title
 * @property string $deadline
 * @property string $urgency
 */

class Jobs extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     * 
     * 
     */
    public $image;

    public static function tableName()
    {
        return 'jobs';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['users_id', 'title', 'deadline', 'urgency'], 'required'],
            [['users_id'], 'integer'],
            [['content'], 'string'],
            [['deadline'], 'required'],
            [['urgency'], 'string'],
            [['urgency'], 'safe'],
            [['image'],'file', 'skipOnEmpty'=>true,'extensions' => 'png,gif,jpg'],
            [['title'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'users_id' => Yii::t('app', 'Users ID'),
            'content'=>Yii::t('app','Content'),
            'title' => Yii::t('app', 'Title'),
            'deadline' => Yii::t('app', 'Deadline'),
            'urgency' => Yii::t('app', 'Urgency'),
            'image' => Yii::t('app', 'image'),
        ];
    }

}

the view file is here named as (_form.php)

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\web\UploadedFile;
//use kartik\widgets\FileInput;

/* @var $this yii\web\View */
/* @var $model app\models\Jobs */
/* @var $form yii\widgets\ActiveForm */


?>
<div class="jobs-form">
<?php 

   $form = ActiveForm::begin([

        'options' => ['enctype' => 'multipart/form-data']]); ?>

    <?= $form->field($model, 'users_id')->textInput() ?>

    <?= $form->field($model, 'content')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'deadline')->textInput() ?>

    <?= $form->field($model, 'urgency')->dropDownList([ 'No', 'yes', ], ['prompt' => '']) ?>


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

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

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

</div>


    enter code here

plzz help me to upload the image in database i dont know what the problem with this code.

解决方案

change your upload code like below:

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

            $image = UploadedFile::getInstance($model,'image');

            $imagepath='upload/jobs/';

            $rand_name=rand(10,100);

            if ($image)
            {
                $model->image = "category_{$rand_name}-{$image}"; 
            }

                if($model->save()):
                    if($image):
                     $image->saveAs($imagepath.$model->image);
                    endif;
                endif;             
                return $this->redirect(['view', 'id' => $model->id]);
            }                    

这篇关于图像保存在文件夹中,但未保存在 yii2.0 中的数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 07:25