Yii2 file upload

//Model
<?php namespace backend\models; use Yii; use yii\web\UploadedFile; class UploalModel extends \yii\db\ActiveRecord { /** * @var UploadedFile|Null file attribute */ public $file; /** * @return array the validation rules. */ public function rules() { return [ [["file"], "file",], ]; } /**Public Upload Information (Array) File Name Size Suffix Name Limits Update to Remove Existing Pictures for Update Pictures*/ public function upload($img,$name = '/vessel',$siez = '',$arr_type = '',$text_name = '',$act='update',$url='/vessel/20180831/153571385083726.jpg') { $path = '../..'; $dirname = $path.$name; $fill=$this->file->extension;//The name of the picture is suffix only. if(empty($text_name)){ $ran=time().rand(10000,99999);//Random name }else{$ran = $text_name;} $arr = $arr_type; if(!empty($arr)){ if(!in_array($fill,$arr)){ return json_encode('Incorrect format);} } //Define upload size and type if(!empty($siez)){ if($img['size']>$siez) {return json_encode('File size exceeds limit.);} } //Files uploaded and stored $dir=$dirname.'/'.date("Ymd"); $dir_sev=$name.'/'.date("Ymd");/*Database storage path*/ if(!file_exists($dir)) { mkdir($dir,0777,true); } if ($this->validate()) { //file name $fileName = $ran .'.'.$fill; $dir = $dir."/". $fileName; if($act == 'update'){if($this->file->saveAs($dir)){@unlink($path.$url);}}/*Delete the picture*/ $uploadSuccessPath = $dir_sev."/". $fileName;/*Final path*/ return $uploadSuccessPath; } } }
//Controller
<?php namespace backend\controllers; use Yii; use backend\models\UploalModel; use yii\web\UploadedFile; class TestController extends \yii\web\Controller { /** * File upload* we return the address of the picture after the upload is successful.*/ public function actionIndex () { $model = new UploalModel(); $uploadSuccessPath = ""; if (Yii::$app->request->isPost) { $model->file = UploadedFile::getInstance($model, "file"); $file = $model->upload((array)$model->file); return $file; } return $this->render("index", [ "model" => $model, "uploadSuccessPath" => $uploadSuccessPath, ]); } }
//view
<?php use yii\widgets\ActiveForm; $form = ActiveForm::begin(["options" => ["enctype" => "multipart/form-data"]]); ?> <input type="hidden" name="UploalModel[file]" value=""> <input type="file" id="uploalmodel-file" name="UploalModel[file]"> <button>Submit</button> <?php ActiveForm::end(); ?>

 

Leave a Reply

Your email address will not be published. Required fields are marked *