Create Uploads table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | CREATE TABLE `uploads` ( `id` int (11) NOT NULL , `category` varchar (45) DEFAULT NULL , `excelFile` varchar (255) DEFAULT NULL , `path` varchar (45) DEFAULT NULL , `dateUploaded` datetime DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `uploads` ADD PRIMARY KEY (`id`); ALTER TABLE `uploads` MODIFY `id` int (11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; COMMIT ; <span style= "background-color:#f3f6f8;font-family:Monaco, Consolas, 'Andale Mono', 'DejaVu Sans Mono', 'Courier 10 Pitch', Courier, monospace;" > |
Create Models, Views and Controllers for Uploads table.
Create a form with these input.
1 2 3 4 5 | </ pre > < div class = "uploads-form" >['enctype' =>'multipart/form-data']]); ?> field($model, 'category')->widget(Select2::classname(), [ 'data' => ArrayHelper::map(Category::find()->all(),'name','name'), 'language' => 'en', 'options' => ['placeholder' => 'Select Semester'], 'pluginOptions' => [ 'allowClear' => true ], ]);?> field($model, 'excelFile[]')->fileInput(['multiple'=>true]) ?> < div class = "form-group" >'btn btn-success']) ?></ div > </ div > < pre > |
Modify your Uploads model. Change type of excelFile, add extensions and skipOnError.
1 2 3 | [[ 'excelFile' ], 'file' , 'extensions' => 'xls, xlsx' , 'maxFiles' => 5, 'skipOnEmpty' =>false, 'wrongExtension' => '{extensions} files only' , 'on' => 'update' ], |
Modify your controller create function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public function actionCreate() { $model = new Uploads(); if ( $model ->load(Yii:: $app ->request->post())) { $model ->excelFile = UploadedFile::getInstances( $model , 'excelFile' ); if ( $model ->excelFile && $model ->validate()){ if (! file_exists ((Url::to( 'uploads/' )))){ mkdir (Url::to( 'uploads/' ), 0777, true); } $path =Url::to( 'uploads/' ); foreach ( $model ->excelFile as $excelFile ){ $excel = new Uploads(); $excel ->category = $model ->category; $count = Uploads::find()->where([ 'category' => $model ->category])-> count (); $fileNo = $count +1; $excel ->excelFile = $model ->category. '_' . $fileNo . '.' . $excelFile ->extension; $excel ->path = 'uploads/' . $excel ->excelFile; if ( $excel ->save()){ $excelFile ->saveAs( $excel ->path, $excel ->excelFile); } } return $this ->redirect([ 'index' ]); } } return $this ->render( 'create' , [ 'model' => $model , ]); |
0 Comments