多文件上载在yii2中不起作用
未使用Yi2上载多个文件,数据未保存到数据库中。显示此错误的htmlspecialchars()要求参数1为字符串,数组为给定数组 我的表格:多文件上载在yii2中不起作用,yii2,Yii2,未使用Yi2上载多个文件,数据未保存到数据库中。显示此错误的htmlspecialchars()要求参数1为字符串,数组为给定数组 我的表格: echo $form->field($model, 'product_img[]')->fileInput(['multiple' => true]); 型号: { return [ [['product_img'],'file', 'maxFiles' => 2], ]; } 控制器: p
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,
]);
}
}
控制器操作中的以下行是错误的
$model2->product_img='uploads/' . $file;
$file
是对象而不是字符串
您可能需要将该行更改为
$model2->product_img = 'uploads/' .$file->baseName;
或者如果您打算稍后使用此列访问该文件
$model2->product_img = 'uploads/' .$file->baseName . '.' . $file->extension;
IlakkiyaM给出了一个答案。请检查其工作情况,查看如何保存模型,无需插入查询。