多个文件上传在yii2中不起作用

时间:2016-07-27 08:47:56

标签: yii2

多个文件未使用yii2上传,数据未保存到数据库中。显示此错误htmlspecialchars()要求参数1为字符串,给定数组。

Myform:

  echo $form->field($model, 'product_img[]')->fileInput(['multiple' => true]); 

型号:

   {
    return [

   [['product_img'],'file', 'maxFiles' => 2],
    ];
}

控制器:

public function actionCreate()
{
    $model = new Product();

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

         $model->file = UploadedFile::getInstances($model, 'product_img');
        foreach ($model->file as $file) {

        $model2 = new Product();

        $model2->load(Yii::$app->request->post());
         $model2->product_img='uploads/' . $file;


        $sql = 'INSERT INTO `product`(`p_id`, `category`, `sub_category`, `product_img`, `product_name`) VALUES (Null,"'.($model2->category).'","'.($model2->sub_category).'","'.($model2->product_img).'","'.($model2->product_name).'")';
        $command = \Yii::$app->db->createCommand($sql);
        $command->execute();
            $file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);

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

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

1 个答案:

答案 0 :(得分:2)

控制器操作中的以下行是错误的

$model2->product_img='uploads/' . $file;

$file是一个非字符串的对象

您可能需要将该行更改为

$model2->product_img = 'uploads/' .$file->baseName;

或者如果您打算稍后使用此列访问该文件

$model2->product_img = 'uploads/' .$file->baseName . '.' . $file->extension;