代码之家  ›  专栏  ›  技术社区  ›  tklustig

如何使用Yii2上传多个文件

  •  1
  • tklustig  · 技术社区  · 7 年前

    以下代码刚刚上传 几个 文件夹。

    <?php
    
    //Code programmed by Thomas Kipp
    //Change it, learn it, do as u please!
    ///path:/models/
    
    namespace frontend\models;
    
    use Yii;
    use yii\base\Model;
    
    class myScriptForm extends Model{ // A new Class programmed by Thomas Kipp 
    
    ...
        public $avatar;
    ...
    
        public function rules() {
            $avatar=array();
            return [
                ['avatar[]','file']]
        }
    
    }
    
    //End of class
    ?>

    以下是我使用SiteController的方法:

        public function actionScript() { //A new method, programmed by Thomas Kipp
            $model = new myScriptForm();
            if ($model->load(Yii::$app->request->post()) && $model->validate()) {
    
                $model->avatar = UploadedFile::getInstances($model, 'avatar[]');
                if ($model->avatar) {
                    echo "<font size='4'><br><center>File <font color='red'> "
                    . "$model->avatar<font color='black'> successfully uploaded."
                    . "<br>It's available in folder 'uploadedfiles' </font></font color></center>";
                    $model->avatar->saveAs(Yii::getAlias('@uploadedfilesdir/' . $model->avatar->baseName . '.' . $model->avatar->extension));
                } else
                    echo"<font size='4'><br><center>No Upload-file selected.<br>"
                    . "Nothing moved into folder 'uploadedfiles' </font></center>";
                return $this->render('myScript', ['model' => $model]);
            }
            else {
                return $this->render('myScript_Formular', ['model' => $model]);
            }
        }
    还有我的公式,没有上传几个文件:
    <?=
    $form->field($model,'avatar[]')->widget(FileInput::classname(), ['options' => ['accept' => 'image/*', 'multiple' => true],])
    ?>
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Yupik    7 年前

    首先,如果你有 echo (...) 在控制器中-你做错了什么。

    在你的代码中,你没有对上传的文件进行任何处理,所以它只保存了一个。

    Yii2 - Uploading Multiple Files -这里有关于如何上传多个文件的完整指南,并附有示例等。

        2
  •  0
  •   Vivek Parmar    7 年前

    <?= $form->field($model, 'image_files[]')->fileInput(['multiple' => true,'accept' => 'image/*']) ?>
    

    $imagefiles = UploadedFile::getInstances($model, 'image_files');
    $model->image_files = (string)count($imagefiles);
    
    if (!is_null($imagefiles)) {
        $dirpath = dirname(getcwd());
        foreach ($imagefiles as $file) {
            $productimage = new ProductImages();
            $productimage->image_name = '/admin/uploads/'.$file->baseName.'.'.$file->extension;
            $productimage->product_id = $model->id;
            if ($productimage->save()) {
                $file->saveAs($dirpath . '/admin/uploads/' . $file->baseName . '.' . $file->extension);
            }
        }
    }