首页 文章

如何使用kartik -v / yii2-widget-fileinput在Yii2上加载多个文件?

提问于
浏览
0

我决定使用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
        ],
    ]); ?>

Controller/action

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,
        ]);
    }

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],
        ];
    }

This is printed

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

Result

事实证明,数组中只有最后一个文件 . 如果我不使用这个小部件,那么一切都是正常加载的数组 .

如何加载和处理一系列照片?

1 回答

  • 0

    我已经做好了 .

    <? echo FileInput::widget([
    'name' => $model->formName() . '[imageFiles][]',
    'options' => ['multiple' => true],
    'pluginOptions' => [
        'previewFileType' => 'any',
        'showPreview' => true,
        'showCaption' => true,
        'showRemove' => true,
        'showUpload' => false,
        'uploadClass' => 'hide',
        'overwriteInitial'=>false,
        'initialPreviewAsData'=>true,
        'fileActionSettings' =>['showUpload' => false],
        'maxFileCount' => 10
    ],
    

    ]); ?>

    这很有效

相关问题