如何使用 Yii2 上传多个文件 [英] How to upload several files using Yii2
本文介绍了如何使用 Yii2 上传多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码只上传一个文件而不是几个文件.任何想法,如何解决?这是我的模型:
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
?>
这是我的 SiteController 方法:
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],])
?>
推荐答案
首先,如果你在控制器中有类似 echo (...)
的东西 - 你做错了什么.
First of all, if you have something like echo (...)
in controller - youre doing something wrong.
在你的代码中你没有对上传的文件做任何 foreach,所以它只保存了一个.
In your code youre not doing any foreach over uploaded files, so it's saving only one.
Yii2 - 上传多个文件 - 这里有关于如何上传多个文件的完整指南,包括示例等.
Yii2 - Uploading Multiple Files - here you have full guide how to upload multiple files, with examples etc.
这篇关于如何使用 Yii2 上传多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文