Save Multiple Image Files Using Kartik FileInput Widget

kaynewilder picture kaynewilder · Sep 18, 2015 · Viewed 10k times · Source

I am currently using Yii2 PHP framework and Kartik FileInput widget in my system. I have used followed this guide of input file uploads on multiple files but it didn't work in my system. I am currently using MongoDB as my database. Here's my progress so far (original, single upload only):

Controller, actionCreate

if($model->load(Yii::$app->request->post())) {   

    $model->attachment = UploadedFile::getInstance($model, 'attachment');

    if($model->attachment) {
        $path = 'archive/contact/' . $model->attachment->baseName . '.' . $model->attachment->extension;
        $count = 0;
        {
            while(file_exists($path)) {
               $path = 'archive/contact/' . $model->attachment->baseName . '_'.$count.'.' . $model->attachment->extension;
               $count++;
            }
        }
        $model->attachment->saveAs($path);
        $model->attachment =  $path;
    }

    $model->save();

} else {
    return $this->renderAjax('create', [
        'model' => $model,
    ]);
}   

View

echo FileInput::widget([
    'model' => $model,
    'attribute' => 'attachment[]',
    'name' => 'attachment[]',
    'options' => [
        'multiple' => true,
        'accept' => 'image/*'
    ],
    'pluginOptions' => [
        'showCaption' => false,
        'showRemove' => false,
        'showUpload' => false,
        'browseClass' => 'btn btn-primary btn-block',
        'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
        'browseLabel' =>  'Attach Business Card',
        'allowedFileExtensions' => ['jpg','gif','png'],
        'overwriteInitial' => false
    ],
]);

I'll also be including my Model

class Contact extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function collectionName()
    {
        return ['iaoy', 'contact'];
    }

    /**
     * @inheritdoc
     */
    public function attributes()
    {
        return [
            '_id', 'fname','lname','email','phone','address','contact_type','business_name','notes','company_id','date_added','attachment','sort'
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['_id', 'fname','lname','email','phone','address','contact_type','business_name','notes','company_id','date_added','attachment','sort'], 'safe'],
            [['fname','lname','contact_type','business_name'], 'required'],
            [['attachment'], 'file', 'extensions' => ['png', 'jpg', 'gif'], 'maxSize' => 500*500],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            //'contact_id' => 'Contact ID',
            '_id' => 'Contact ID',
            'contact_type' => 'Contact Type',
            'business_name' => 'Business Name',
            'fname' => 'First Name',
            'lname' => 'Last Name',
            'email' => 'Email',
            'phone' => 'Phone',
            'address' => 'Address',
            'notes' => 'Notes',
            'attachment' => 'Attachment',
            'company_id' => 'Company ID',
        ];
    }
}

How do I implement the multiple file upload having this already implemented? Any thoughts are highly appreciated.

EDIT:

Here's my multi file upload code so far. I didn't mixed it with my current code (single file upload) instead I made a new MVC. It's just basically what I found in the guide I mentioned above with just very little modifications:

Model

<?php

namespace app\models;

use yii\base\Model;
use yii\web\UploadedFile;

class Upload extends Model
{
    public $file;

    public function attributes()
    {
        return [
            'file', 'urls'
        ];
    }

    public function rules()
    {
        return [
            [['file', 'urls'], 'safe'],
            [['file'], 'file','extensions' => 'png, jpg'],
            [['urls'],'string'],
        ];
    }
}

View

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\file\FileInput;

    $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]);
?>

    <?php
        echo FileInput::widget([
            'model' => $model,
            'attribute' => 'file[]',
            'name' => 'file[]',
            'options' => [
                'multiple' => true,
                'accept' => 'image/*'
            ],
            'pluginOptions' => [
                'showCaption' => false,
                'showRemove' => false,
                'showUpload' => false,
                'browseClass' => 'btn btn-primary btn-block',
                'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
                'browseLabel' =>  'Attach Business Card',
                'allowedFileExtensions' => ['jpg','gif','png'],
                'overwriteInitial' => false
            ],
        ]);
    ?>
     <button>Submit</button>

<?php ActiveForm::end(); ?>

Controller

public function actionUpload()
{
    $model = new Upload();

    if ($model->load(Yii::$app->request->post())) {
        $model->file = UploadedFile::getInstances($model, 'file');

        foreach ($model->file as $key => $file) {
            $file->saveAs('archive/reimbursement/'. $file->baseName . '.' . $file->extension);//Upload files to server
            $model->urls .= 'archive/reimbursement/' . $file->baseName . '.' . $file->extension.'**';//Save file names in database- '**' is for separating images
        }
        $model->save();
        return $this->redirect(['viewuploads', 'id' => $model->id]);
    } else {
        return $this->render('upload', [
            'model' => $model,
        ]);
    }
}

I also added 'urls' in my Contact.php model rules function

Answer

Amin Shafiee picture Amin Shafiee · Sep 18, 2015

Try this:

Controller: you should save image name in database('$model->urls')

public function actionUpload()
{
        $model = new Upload();

        if ($model->load(Yii::$app->request->post())) {
            $model->file = UploadedFile::getInstances($model, 'file');
            foreach ($model->file as $key => $file) {

                $file->saveAs('/uploads/'. $file->baseName . '.' . $file->extension);//Upload files to server
                $model->urls .= 'uploads/' . $file->baseName . '.' . $file->extension.'**';//Save file names in database- '**' is for separating images
            }
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('upload', [
                'model' => $model,
            ]);
        }
}

View

<?= $form->field($model, 'file[]')->widget(FileInput::classname(), [
'options' => ['multiple' => 'true'],
]) ?>

Model

class Upload extends Model
{
public $file;
public function rules()
{
    return [
        [['file'], 'file','maxFiles' => 6],
        [['urls'],'string'],

    ];
}

Another view for showing images

<?php
$images=explode('**',trim($model->urls));
foreach($images as $image)
{
     echo Html::img(Url::to('@web/' . $image, true));
}
?>