分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

yii2文件上传

发布时间:2023-09-06 02:12责任编辑:彭小芳关键词:文件上传
//模型
<?phpnamespace 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",], ???????]; ???} ???/**公共上传 上传信息(数组) 文件名称 大小 后缀名限制 上传后保存的名字 update时为更新图片 删除原有图片*/ ???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;//图片的名字只取后缀名 ???????if(empty($text_name)){ ???????????$ran=time().rand(10000,99999);//随机名字 ???????}else{$ran = $text_name;} ???????$arr = $arr_type; ???????if(!empty($arr)){ ???????????if(!in_array($fill,$arr)){ return json_encode(‘格式不正确‘);} ???????} ???????//定义上传大小和类型 ???????if(!empty($siez)){ ???????????if($img[‘size‘]>$siez) {return json_encode(‘文件大小超过限制‘);} ???????} ???????//文件上传存放的目录 ???????$dir=$dirname.‘/‘.date("Ymd"); ???????$dir_sev=$name.‘/‘.date("Ymd");/*数据库存储路径*/ ???????if(!file_exists($dir)) { ???????????mkdir($dir,0777,true); ???????} ???????if ($this->validate()) { ???????????//文件名 ???????????$fileName = $ran .‘.‘.$fill; ???????????$dir = $dir."/". $fileName; ???????????if($act == ‘update‘){if($this->file->saveAs($dir)){@unlink($path.$url);}}/*删除图片*/ ???????????$uploadSuccessPath = $dir_sev."/". $fileName;/*最后路径*/ ???????????return $uploadSuccessPath; ???????} ???}}
//控制器
<?phpnamespace backend\controllers;use Yii;use backend\models\UploalModel;use yii\web\UploadedFile;class TestController extends \yii\web\Controller{ ???/** ????* ???文件上传 ????* ?我们这里上传成功后把图片的地址进行返回 ????*/ ???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, ???????]); ???}}
//视图
<?phpuse 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(); ?>

yii2文件上传

原文地址:https://www.cnblogs.com/5aiQ/p/9567602.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved