---------------------------------------------------------------------------------------------------
首先你得调整模型类,在 file
验证规则里增加一个 maxFiles
选项,用以限制一次上传文件的最大数量。
upload()
方法也得修改, 以便一个一个地保存上传的文件。
---------------------------------------------------------------------------------------------------
<?php
namespace appmodels;
use yiiaseModel;
use yiiwebUploadedFile;
class UploadForm1 extends Model{
/**
* @var UploadedFile[]
*/
public $imageFiles;
public function rules()
{
return [
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 4],
];
}
public function upload()
{
foreach ($this->imageFiles as $file) {
$file->saveAs('./upload/' . $file->baseName . '.' . $file->extension);
}
return true;
}
}
--------------------------------------------------------------------------------------------------------------
在视图文件里,你需要把 multiple
选项添加到fileInput()
函数调用里, 这样文件输入控件就可以接收多个文件。
---------------------------------------------------------------------------------------------------------------
<?php
use yiiwidgetsActiveForm;
use yiihelpersUrl;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<table class="table table-bordered table-hover definewidth m10">
<tr>
<td class="tableleft">上传多个图片</td>
<td><?= $form->field($model, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
</td>
</tr>
<tr>
<td class="tableleft"></td>
<td>
<button type="submit" class="btn btn-primary" type="button">保存</button>
</td>
</tr>
<?php ActiveForm::end() ?>
-------------------------------------------------------------------------------------------------------------
最后,在控制器的 action 方法中,你应该调用 UploadedFile::getInstances()
而不是 UploadedFile::getInstance()
来把UploadedFile
实例数组赋值给 UploadForm::imageFiles
。
------------------------------------------------------------------------------------------------------------
<?php
namespace backendcontrollers;
use Yii;
use yiiwebController;
use appmodelsUploadForm1;
use yiiwebUploadedFile;
class PhotoController extends Controller
{
public $enableCsrfValidation = false;
public function actionIndex()
{
$request = Yii::$app->request;
$model = new UploadForm1();
if($request->isPost)
{
$file=$model->imageFiles = UploadedFile::getInstances($model, 'imageFiles');
//print_r($file);die;
foreach ($file as $key => $v) {
$image[]=$v->name;
}
//print_r($image);die;
$images=implode(',',$image);
if($model->upload())
{
$connection = Yii::$app->db;
$connection->createCommand()->insert('upload', [
'image' => $images,
])->execute();
}
}
else
{
return $this->render('upload1',['model' => $model]);
}
}
}