【问题标题】:multiple file upload not working in yii2多个文件上传在yii2中不起作用
【发布时间】:2016-07-27 08:47:55
【问题描述】:

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

我的表格:

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

【问题讨论】:

  • 它不适合我。
  • @IlakkiyaM 发布了答案。请检查它是否工作
  • 查看如何保存模型,无需插入查询

标签: yii2


【解决方案1】:

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

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

$file 是一个对象而不是字符串

您可能需要将该行更改为

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

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

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

【讨论】:

    猜你喜欢
    • 2015-12-20
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 2013-12-08
    • 1970-01-01
    相关资源
    最近更新 更多