在yii2中上传多个图像不起作用!
视图:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($uploadModel, 'imageFiles[]')->fileInput(['multiple' => 'multiple', 'accept' => 'image/*']) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
控制器:
$uploadModel = new \app\models\UploadForm();
if (Yii::$app->request->isPost) {
$uploadModel->imageFiles = \yii\web \UploadedFile::getInstance($uploadModel, 'imageFiles');
if ($uploadModel->upload()) {
echo 'successfully';
return true;
}else{
echo 'failed';
}
} else {
return $this->render('create', [
'model' => $model,
'uploadModel' => $uploadModel,
]);
}
uploadModel:
public $imageFiles;
public function rules() {
return [
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'maxFiles' => 10, 'extensions' => 'png, jpg'],
];
}
public function upload() {
if ($this->validate()) {
foreach ($this->imageFiles as $file) {
$file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
}
return true;
} else {
return false;
}
}
我对kartik文件输入小部件有同样的问题!
答案 0 :(得分:1)
要返回给定模型属性的所有上传文件,您必须调用
UploadedFile::getInstances($model, 'imageFiles');
的实例
UploadedFile::getInstance($model, 'imageFiles');
参考: Yii::UploadFile