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

1 回答 1

0

我看到一个问题是你颠倒了 $images 和 $image

foreach ($image as $images)

应该是

foreach ($images as $image)

干杯

于 2017-10-04T20:47:45.000 回答