Yii2 Basic在创建内容时上传多个图像

时间:2018-03-29 09:31:15

标签: yii2 yii2-basic-app

我在创建Post时尝试上传多个图像,但只有一个Image存储在数据库中,在服务器中保存所有图像但在我的表中只保存了第一个图像但不是全部因此我创建了上传功能

// Function to upload images
public function CreateGallery($model_Post, $model_Gallery)
{
    $model_Post->Post_id = md5(microtime());
    $model_Post->User_id = Yii::$app->user->id;

    $GLRID = md5(uniqid());

    // file
    $GFolder = 'upload/images/'. $model_Post->Post_id .'/' ;

    mkdir ($GFolder, 0777, true);

    if ( $model_Post->save() ){

        $model_Gallery->GalleryFile = UploadedFile::getInstances($model_Gallery, 'GalleryFile');

        $ly_GalName = uniqid();

        foreach ($model_Gallery->GalleryFile as $GalleryImage) {

            ++$ly_GalName;
            $model_Gallery->Gallery_id = ++$GLRID;
            $model_Gallery->User_id = $model_Post->User_id;
            $model_Gallery->Post_id =  $model_Post->Post_id;

            $GalleryImage->saveAs($GFolder . $GalName . '.' . $GalleryImage->extension);

            $model_Gallery->Gallery_image = $GFolder . $GalName . '.' . $GalleryImage->extension;
        }
        $model_Gallery->save(false);
    }   
}

在我的控制器内部添加了我创建的功能

public function actionCreate()
{
    $model_Post = new Post(); 
    $model_Gallery = new Gallery;
    $actions_UploadImages = new ActionsUploadImages();

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

        $actions_UploadImages->CreateGallery($model_Post, $model_Gallery)

        return $this->redirect(['view', 'id' => $model_Post->Post_id]);
    } else {
        return $this->render('create', [
            'model_Post' => $model_Post,
            'model_Gallery' => $model_Gallery,
        ]);
    }
}

和我的观点/创建我的代码是

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

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

<?= $form->field($model_Gallery, 'GalleryFile[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>

<?= $form->field($model_Post, 'Post_text')->textarea(['rows' => 2]) ?>

<?= $form->field($model_Post, 'Permission_id')->dropdownList($model_Permission->PermissionList()) ?>

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

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

我尝试将gallery_id更改为AUTO_INCREMENT,但仍然存在同样的问题,我尝试删除if($ model_Post-&gt; save()),但是我从数据库中收到错误。现在它只是保存在服务器上的所有图像,但在表格中只保存一个图像。

//// gallery model:

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "gallery".
 *
 * @property string $Gallery_id
 * @property string $Gallery_image
 * @property string $Post_id
 * @property string $User_id
 *
 * @property Post $post
 * @property Userlogin $user
 */
class Gallery extends \yii\db\ActiveRecord
{
    public $GalleryFile;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'gallery';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['Gallery_id', 'Post_id', 'User_id'], 'required'],
            [['Gallery_id'], 'string', 'max' => 200],
            [['Gallery_image'], 'string', 'max' => 350],
            [['Post_id', 'User_id'], 'string', 'max' => 300],
            [['GalleryFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, jpeg, gif', 'maxFiles' => 5],
            [['Post_id'], 'exist', 'skipOnError' => true, 'targetClass' => Post::className(), 'targetAttribute' => ['Post_id' => 'Post_id']],
            [['User_id'], 'exist', 'skipOnError' => true, 'targetClass' => Userlogin::className(), 'targetAttribute' => ['User_id' => 'User_id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'Gallery_id' => 'Gallery ID',
            'Gallery_image' => 'Gallery Image',
            'Post_id' => 'Post ID',
            'User_id' => 'User ID',
        ];
    }


    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPost()
    {
        return $this->hasOne(Post::className(), ['Post_id' => 'Post_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(Userlogin::className(), ['User_id' => 'User_id']);
    }

    /**
     * @inheritdoc
     * @return \app\queries\GalleryQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \app\queries\GalleryQuery(get_called_class());
    }
}

2 个答案:

答案 0 :(得分:1)

你需要为每个人写一个新的模型,比如

<强>功能

  • 在for each中创建一个新的模型对象。
  • 在foreach中设置$model_Gallery->save(false);

    //上传图片的功能

    public function CreateGallery($model_Post, $model_Gallery)
    {
        $model_Post->Post_id = md5(microtime());
        $model_Post->User_id = Yii::$app->user->id;
        $GLRID = md5(uniqid());
        // file
        $GFolder = 'upload/images/' . $model_Post->Post_id . '/';
    
        mkdir($GFolder, 0777, true);
    
        if ($model_Post->save()) {
            $model_Gallery->GalleryFile = UploadedFile::getInstances($model_Gallery, 'GalleryFile');
    
            $ly_GalName = uniqid();
    
            foreach ($model_Gallery->GalleryFile as $GalleryImage) {
                $model_GalleryImage = new Gallery;
                ++$ly_GalName;
                $model_GalleryImage->Gallery_id = ++$GLRID;
                $model_GalleryImage->User_id = $model_Post->User_id;
                $model_GalleryImage->Post_id = $model_Post->Post_id;
    
                $GalleryImage->saveAs($GFolder . $GalName . '.' . $GalleryImage->extension);
    
                $model_GalleryImage->Gallery_image = $GFolder . $GalName . '.' . $GalleryImage->extension;
                $model_GalleryImage->save(false); //here , remove 'false' to work validations
            }
    
        }
    } 
    

控制器

当动作加载数据时,它应该不是那样的?

if ($model_Gallery->load(Yii::$app->request->post()) and  $model_Post->load(Yii::$app->request->post())) {
        //the rest of the code
        }
  

请注意,我们使用save(false)跳过模型内的验证作为用户输入数据...用户输入

答案 1 :(得分:0)

您所要做的就是使用foreach循环迭代$ _FILES对象并每次创建新模型。验证代码管理标志