我决定使用 FileInput Widget 上传几个图像文件
<?= $form->field($model, 'imageFiles[]')->widget(FileInput::classname(),[
'name' => 'imageFiles[]',
'attribute' => 'imageFiles[]',
'options' => ['multiple' => true],
'pluginOptions' => [
'previewFileType' => 'any',
'showPreview' => true,
'showCaption' => true,
'showRemove' => true,
'showUpload' => false,
'uploadClass' => 'hide',
'overwriteInitial'=>false,
'initialPreviewAsData'=>true,
'uploadUrl' => Url::to(['/site/image-manager-upload']),
'fileActionSettings' =>['showUpload' => false],
'maxFileCount' => 10
],
]); ?>
控制器/动作
public function actionCreate()
{
$model = new Hotel();
$model->load(Yii::$app->request->post());
$model->imageFiles = UploadedFile::getInstances($model, 'imageFiles');
var_dump($model->imageFiles);die();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}
模型
class Hotel extends \yii\db\ActiveRecord
{
const STATUS_OFF = 0;
const STATUS_ON = 1;
const TYPE_POINTS = 0;
const TYPE_STARS = 1;
public $imageFiles;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'hotel';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name', 'url', 'reting_id', 'reting_type'], 'required'],
[['text'], 'string'],
[['reting_id', 'reting_type', 'status', 'created_at', 'updated_at'], 'integer'],
[['name', 'url'], 'string', 'max' => 255],
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 4],
];
}
这是打印的
array(1) {
[0]=> object(yii\web\UploadedFile)#168 (5) {
["name"]=> string(12) "IMG_2793.jpg"
["tempName"]=> string(36) "C:\OSPanel\userdata\temp\phpC2A1.tmp"
["type"]=> string(10) "image/jpeg"
["size"]=> int(264672) ["error"]=> int(0)
}
结果
事实证明,数组中只有最后一个文件。如果我不使用这个小部件,那么一切都是正常加载的数组。
我怎样才能加载和处理一组照片?