【问题标题】:image are save in folder but not saved in database in yii2.0yii2.0中图像保存在文件夹中但不保存在数据库中
【发布时间】:2016-02-29 13:34:24
【问题描述】:

我是 yii 的新手,我以前在数据库中上传图像,但图像存储在文件夹中但未保存在数据库中,这段代码有什么问题不能理解

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

模型在这里被命名为 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'),
        ];
    }

}

视图文件在这里命名为 (_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

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

【问题讨论】:

    标签: yii2


    【解决方案1】:

    如下更改您的上传代码:

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

    【讨论】:

      【解决方案2】:

      您在代码中混合了图像名称和图像文件。 如果image 是您的数据库表中的一个字段,则public $image 是不必要的。而是在您的模型中添加public $imageFile,并相应地更新您的表单和控制器。

      请记住,$this-&gt;image$model-&gt;image 是字符串形式的图像名称,您正在混入上传对象。而是创建另一个变量,以便您可以存储上传的图像,并使用图像变量保存实际名称以供以后参考。

      看看你能不能弄明白,如果你不能让它发挥作用,请更新你的问题。

      http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html

      【讨论】:

        猜你喜欢
        • 2017-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-11
        • 1970-01-01
        • 2021-08-12
        • 2016-04-06
        • 1970-01-01
        相关资源
        最近更新 更多