如何使用Yii2上传多个文件

时间:2017-06-29 08:18:59

标签: yii2

以下代码只需上传一个文件,而不是多个文件。 任何想法,如何解决? 这是我的模特:



<?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
?>
&#13;
&#13;
&#13;

这是我的SiteController方法:

&#13;
&#13;
    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]);
        }
    }
&#13;
&#13;
&#13; 仍然是我的Formular,它没有上传多个文件:

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

2 个答案:

答案 0 :(得分:1)

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

在您的代码中,您没有对上传的文件进行任何预测,因此它只保存了一个。

Yii2 - Uploading Multiple Files - 在这里您可以获得如何上传多个文件的完整指南,以及示例等。

答案 1 :(得分:0)

下面的代码对我有用,希望这对你有帮助,

查看文件=&gt;

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

Controller =&gt;

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