首页 文章

Yii2 kartik文件FileInput Multiple

提问于
浏览
0

所以我正在和Yii2合作并且对它很新 . 我正在使用Kartik文件上传,并试图转换多个文件的代码 . 但它只保存第一个文件 .

我已经删除了验证,因为这也失败了,但是一旦我知道其他所有工作就会重新加入 .

模型:

/**
    * Process upload of image
    *
    * @return mixed the uploaded image instance
    */
    public function uploadImage() {

        // get the uploaded file instance. for multiple file uploads
        // the following data will return an array (you may need to use
        // getInstances method)
         $image = UploadedFile::getInstances($this, 'image');

         foreach ($image as $images) {

        // if no image was uploaded abort the upload
        if (empty($images)) {

            return false;
        }
        // store the source file name
        $this->image_src_filename = $images->name;
        $extvar = (explode(".", $images->name));
        $ext = end($extvar);


        // generate a unique file name
        $this->image_web_filename = Yii::$app->security->generateRandomString().".{$ext}";

        // the uploaded image instance

        return $images;


} }

控制器:

/**
     * Creates a new PhotoPhotos model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new PhotoPhotos();

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

            // process uploaded image file instance
            $images = $model->uploadImage();



         if ($model->save(false)) {

            // upload only if valid uploaded file instance found
                if ($images !== false) {

                    $path = $model->getImageFile();
                    $images->saveAs($path);

                }

            return $this->redirect(['view', 'id' => $model->ID]);
        } else {
            //error in saving

        }

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

视图:

//uncomment for multiple file upload
echo $form->field($model, 'image[]')->widget(FileInput::classname(), [
    'options'=>['accept'=>'image/*', 'multiple'=>true],
]);

1 回答

  • 0

    我看到一个问题是你扭转了$ images和$ image in

    foreach ($image as $images)
    

    应该是

    foreach ($images as $image)
    

    干杯

相关问题