1

multiple file not uploaded using yii2,data are not saved into database.It showing this error htmlspecialchars() expects parameter 1 to be string, array given.

Myform:

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

Model:

   {
    return [

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

Controller :

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,
        ]);
    }
}
4
  • Yii2 upload multiple files Commented Jul 27, 2016 at 8:54
  • its not working for me. Commented Jul 27, 2016 at 9:03
  • @IlakkiyaM Posted an answer . Please check if its working Commented Jul 27, 2016 at 9:17
  • see how to save model, no need for insert query. Commented Jul 27, 2016 at 10:21

1 Answer 1

2

Following line in your controller action is wrong

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

$file is an object not string

You may need to change that line to

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

or if you intend to access the file later using this column

$model2->product_img = 'uploads/' .$file->baseName . '.' . $file->extension;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.