How to upload several files using Yii2

2019-07-27 07:19发布

问题:

Following code just uploads one file instead several files. Any ideas, how to fix that? Here is my model:

<?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
?>

Here is my method of 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]);
        }
    }
and still my Formular, which is not uploading several files:

<?=
$form->field($model,'avatar[]')->widget(FileInput::classname(), ['options' => ['accept' => 'image/*', 'multiple' => true],])
?>

回答1:

First of all, if you have something like echo (...) in controller - youre doing something wrong.

In your code youre not doing any foreach over uploaded files, so it's saving only one.

Yii2 - Uploading Multiple Files - here you have full guide how to upload multiple files, with examples etc.



回答2:

Below code works for me, hope this will help you,

View file =>

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

Controller =>

$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);
        }
    }
}


标签: yii2