2016-07-27 42 views
1

多個文件沒有上傳使用yii2,數據沒有保存到數據庫。它顯示此錯誤htmlspecialchars()期望參數1是字符串,給定的數組。多個文件上傳不工作在yii2

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

[Yii2上傳多個文件訪問該文件](http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html#uploading-multiple-files) –

+0

它不適合我。 –

+0

@IlakkiyaM已發佈一個答案。請檢查其工作 –

回答

2

繼控制器行動路線是錯誤的

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

$file是一個對象,不串

您可能需要到該行更改爲

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

,或者如果您打算在以後通過此列

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