如何在Yii2中的两个不同路径上传两个文件?

时间:2015-08-04 12:10:54

标签: php mysql yii2

public function actionCreate()
{
        $model = new RoomTypes();
        if ($model->load(Yii::$app->request->post())) 
        {
            $imageName_1 = $model->room_type.'_'.'1';
            $model->pic_1 = UploadedFile::getInstance($model, 'pic_1');
            $model->pic_1->saveAs('uploads/room_pics/'.$imageName_1.'.'.$model->pic_1->extension);
            $model->pic_1 = 'uploads/room_pics/'.$imageName_1.'.'.$model->pic_1->extension;

            $imageName_2 = $model->room_type.'_'.'2';
            $model->pic_2 = UploadedFile::getInstance($model, 'pic_2');
            $model->pic_2->saveAs('uploads/room_pics/'.$imageName_2.'.'.$model->pic_2->extension);
            $model->pic_2 = 'uploads/room_pics/pic2/'.$imageName_2.'.'.$model->pic_2->extension;
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else 
        {
            return $this->render('create', [
                'model' => $model,
            ]);
        }  
}

我无法在文件夹中存储第二张图片,此代码将第一张或第二张图片存储在文件夹中,只有一张图片存放不是全部两张,如何实现?

更新 **型号 - **

public function rules()
    {
        return [
            [[/*'room_number','total_people', 'room_type', 'total_count', 'extra_beds', 'pic_1', 'pic_2', 'status', 'rate', 'adults_count', 'child_count'*/], 'required'],
            [['room_number','total_people','total_count', 'extra_beds', 'rate', 'adults_count', 'child_count'], 'integer'],
            [['status'], 'string'],
            [['pic_1', 'pic_2'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 4],
            [['room_type'], 'string', 'max' => 40],
            [['description'], 'string', 'max' => 300],
            [['pic_1', 'pic_2'], 'string', 'max' => 500]
        ];
    } 

1 个答案:

答案 0 :(得分:0)

似乎$model->pic_2作业中的名称错误我在kmore中看到/pic2/

$model->pic_2 = 'uploads/room_pics/pic2/'.$imageName_2.'.'.$model->pic_2->extension;

$model->pic_1 = 'uploads/room_pics/'.$imageName_1.'.'.$model->pic_1->extension;

在下面的代码行中,路径名不适合我

在第二部分,我看到pic2了解更多

        $model->pic_1->saveAs('uploads/room_pics/'.$imageName_1.'.'.$model->pic_1->extension);
        $model->pic_1 = 'uploads/room_pics/'.$imageName_1.'.'.$model->pic_1->extension;

        $model->pic_2->saveAs('uploads/room_pics/'.$imageName_2.'.'.$model->pic_2->extension);
        $model->pic_2 = 'uploads/room_pics/pic2/'.$imageName_2.'.'.$model->pic_2->extension;

在这两个部分中,或者在saveAs中没有匹配,或者在分配时不匹配,当yuo后退你没有找到图片文件的路径时