thinkphp表单上传文件并将文件路径保存到数据库中
程序员文章站
2024-04-02 16:49:58
上传单个文件,此文以上传图片为例,上传效果如图所示
创建数据库upload_img,用于保存上传路径
create table `seminar_u...
上传单个文件,此文以上传图片为例,上传效果如图所示
创建数据库upload_img,用于保存上传路径
create table `seminar_upload_img` ( `id` int(11) not null auto_increment, `img_name` varchar(255) default null comment '图片名称', `img_url` varchar(255) default null comment '图片路径', `create_time` text, primary key (`id`) ) engine=innodb auto_increment=23 default charset=utf8;
在公共配置文件common/conf.php中连接数据库,并配置地址
return array( 'db_type'=>'mysql', 'db_host'=>'127.0.0.1', 'db_name'=>'seminar', 'db_user'=>'root', 'db_pwd'=>'root', 'db_port'=>3306, 'db_prefix'=>'seminar_', 'db_charset'=>'utf8', 'show_page_trace'=>true, /*地址替换*/ 'tmpl_parse_string'=>array( '__upload__'=>__root__.'/public/uploads', ), );
视图文件upload/index.html中
<!doctype html> <html> <head> <title></title> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <style type="text/css"> #img{height:22px; border:#000 2px solid} #button{height:30px; width:100px;} </style> </head> <body> <div><notemply name="data"> <img src="__upload__/{$data['img_url']}" width="200" height="100"/> </notemply></div> <div class="result" >上传允许文件类型:'jpg', 'gif', 'png', 'jpeg'图像文件后</div><br> <form action="{:u('upload/upload')}" method="post" enctype="multipart/form-data"> <input type="file" name="image"/> <input type="submit" value="上传" id="button"> </form> </body> </html>
控制器uploadcontroller.class.php中实现上传文件
namespace home\controller; use think\controller; class uploadcontroller extends controller { public function index() { $img=m('upload_img'); $sel=$img->order('create_time desc')->find(); $this->assign('data', $sel); $this->display(); } public function upload(){ $upload_img=m('upload_img'); if(!empty($_files)){ //上传单个图像 $upload = new \think\upload();// 实例化上传类 $upload->maxsize = 1*1024*1024 ;// 设置附件上传大小 $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型 $upload->rootpath = 'public/uploads/'; // 设置附件上传根目录 $upload->savepath = ''; // 设置附件上传(子)目录 $upload->savename=array('uniqid','');//上传文件的保存规则 $upload->autosub = true;//自动使用子目录保存上传文件 $upload->subname = array('date','ymd'); // 上传单个图片 $info = $upload->uploadone($_files['image']); if(!$info) {// 上传错误提示错误信息 $this->error($upload->geterror()); }else{// 上传成功 获取上传文件信息 $img_url=$info['savepath'].$info['savename']; $data['img_url']=$img_url; $data['img_name']=$info['savename']; $data['create_time']=now_time; $upload_img->create($data); $result=$upload_img->add(); if(!$result){ $this->error('上传失败!'); }else{ $this->success('上传成功'); } } } } }
以上所述是小编给大家介绍的thinkphp表单上传文件并将文件路径保存到数据库中,希望对大家有所帮助