详解ThinkPHP怎么实现图片上传
2022-11-24 11:02:51
184
{{single.collect_count}}
下面由thinkphp框架教程栏目给大家介绍ThinkPHP怎么实现图片上传功能,希望对需要的朋友有所帮助!

直接上个例子,其中包括有单图片文件上传、多图片文件上传、以及删除文件的一些操作、放置删除数据库的时候,仅仅删除掉了数据库之中的文件路径、而不是一并删除服务器之中的文件、放置服务器爆炸...

TP里面common文件夹里面function.php里面自定义方法:

<?php//文件上传类(可以设置多个参数)function upload($file=null,$maxSize=0,$exts=0,$savePath=''){//调用$upload = new \Think\Upload();// 实例化上传类$upload->maxSize= $maxSize;// 设置附件上传大小$upload->exts = $exts; //array('jpg', 'gif', 'png', 'jpeg'); 设置附件上传类型$upload->savePath = $savePath; // 设置附件上传目录// 上传文件//如果单个文件还是多个文件if($file){ $info = $upload->uploadOne($file);}else{$info = $upload->upload();}//判定是否文件上传成功deif(!$info) {return false;}else{// 上传成功,return $info;}}//上传图片function fab_upload($files ,$maxSize = 0,$exts = null,$savePath = ''){//判定文件信息是否为空if(empty($files)){return false;}if($exts === null){$exts = array('jpg', 'gif', 'png', 'jpeg');}else{$exts = 0;}$tmp = array();//将文件信息(数组)用foreach循环遍历,foreach($files as $k => $v){//判定文件大于0之后,将遍历value作为参数传入upload方法if($v['size'] > 0){$res = upload($v,$maxSize,$exts,$savePath);//如果传入成功就会将文件存储路径传入数组$tmp[]之中if($res){$tmp[$k] = $res['savepath'].$res['savename'];}}}//将存储传入文件路径的数组return回去return $tmp;}?>
登录后复制

其实无论哪个文件上传、都是需要用$_FILES变量区操控的、

上面的方法是fab_upload调用upload方法的;

在HTML上我们表单是酱紫写的:

<form action="{:U('Index/infoupload')}" method="post"style="overflow: hidden;clear: both;" enctype="multipart/form-data"><p class="contact_r col-md-4"><label class="contact_rc contact_file"><span><b>入台證:</b><input class="inp_zj1" type="file" name="rutaiimg" ></span></label><!-- <a class="contact_sp fancybox" href="images/txz1.jpg" rel="external nofollow" rel="external nofollow" >如圖示</a> --></p><p class="contact_r col-md-4"><label class="contact_rc contact_file"><span><b>通行證:</b><input class="inp_zj2" type="file" name="tongxingimg" ></span></label><!-- <a class="contact_sp fancybox" href="images/txz1.jpg" rel="external nofollow" rel="external nofollow" >如圖示</a> --></p></form>
登录后复制

控制器之中如何处理上传的文件(拼接路径以及文件名、还有入库失败需要删除文件,类似回调)

/*调用写好的方法进行验证*/$new_thumb = fab_upload($_FILES);// var_dump($new_thumb);die;$input['data']['addtime']=time();//生成申请时间$input['data']['pretime']=strtotime($input['data']['pretime']);//将传过来的日期转换成时间戳if($new_thumb && count($new_thumb) > 0){$input['data'] = array_merge($input['data'],$new_thumb);}$f = $customer->add($input['data']);if($f){$this->display('Index/infosuccess');// $this->success("添加成功!",U('Index/infocheck',array('iccid'=>$input['data']['iccid'])));}else{//数据添加失败即删除照片if($new_thumb){$p = C('UNLINK_PATH').$new_thumb;unlink($p);}$this->error("添加失败!证件可能已存在");}
登录后复制

其中UNLINK_PATH变量在ThinkPHP之中的config文件里面定义、是路径来的

<?phpreturn array('DB_TYPE'=> 'mysql', // 数据库类型'DB_HOST'=> 'localhost', // 服务器地址'DB_NAME'=> 'urban', // 数据库名'DB_USER'=> 'root', // 用户名'DB_PWD'=> '123456', // 密码'DB_PORT'=> 3306, // 端口'DB_PREFIX' => 'fab_', // 数据库表前缀'DB_CHARSET'=> 'utf8', // 字符集'CHECK_ROOT' => true, //开启rbac权限'TMPL_CACHE_ON' => false,// 是否开启模板编译缓存,设为false则每次都会重新编译'ACTION_CACHE_ON' => false, // 默认关闭Action 缓存'HTML_CACHE_ON'=> false,// 默认关闭静态缓存'FILE_PATH'=>'http://localhost/urban/Uploads/','WEB_PATH'=>'http://localhost/urban/index.php/','WEB_URL'=>'http://localhost/urban/','UNLINK_PATH'=>'./Uploads/','PWD_KEY'=> 'jeiskAsdlLsdfqaiocvwphxzbtu','AUTO_LOGIN_TIME'=>3600 * 24 * 7,'SHOW_PAGE_TRACE'=>true, //追踪模式'MY_CATCH_DIR' =>'./cache/', //缓存目录'CODE_PATH' =>'http://localhost/urban/fabp/phpqrcode/',// 存放二维码的目录'qq_face' =>'http://localhost/urban/Public/site/images/arclist/', //qq表情路径'wxlogin' => array('appid' => 'wx35f5b9e9b90539ae','AppSecret' => '4de424bee1529a8abeda9c0c52aad3aa','callback' => 'http://localhost/urban/index.php/Home/Login/call_back.html'),'topic_pass'=>false,//是否开启话题审核);
登录后复制

当添加以后,自然需要在后台管理模块上添加删除的function

上面的显示图片的时候,用HTTP协议的绝对路径拼接出来显示图片;

而删除图片则是,以入口文件index.php为准,是当前文件夹下面的upload文件夹;

记住调用ThinkPHP之中的upload、uploadone方法返回来的只是上传文件在upload文件夹下面的存储位置、“'2016-09-02/57c94e71f0916.png'”(入库也这个吧)

所以无论删除还是显示都需要用C方法拼接一下

if(IS_POST){$input=I('post.');$ids=implode(',',$input['id']);$brand=D('brand');$img=$brand->where("brand_id in ($ids)")->getField('thumb',true);foreach($img as $v){$p = C('UNLINK_PATH').$v;unlink($p);}$res=$brand->where("brand_id in ($ids)")->delete();if($res){$this->success("删除运营商品牌成功!");}else{$this->error("删除运营商品牌失败!");}}
登录后复制

之所以用了那个foreach;是因为传过来的id不是唯一一个;是多选,删除;

多选,并且传过去相应栏目ID的值是如何实现的呢

<foreach name="list" item="v"><tr><td class="center" width="80px"><label><input type="checkbox" class="ace" name="id[]" value="{$v.brand_id}"/><span class="lbl"></span></label></td><td>{$v.brand_name}</td></tr></foreach><tr><td colspan="2"><button class="btn btn-xs btn-danger" onclick="return tijiao('del')"><i class="icon-trash bigger-110"></i>删除</button> </td></tr>
登录后复制

上面删除的javascript方法是这样写的:

<script type="text/javascript">function tijiao(type){if(type == 'del'){$('#my_form').attr('action',"{:U('Admin/Brand/brand_del')}");}else if(type == 'sort'){$('#my_form').attr('action',"{:U('Admin/Brand/brand_sort')}");}return true;}</script>
登录后复制

附加:其实判定文件是否有上传最好用这个数据:

$_FILES['input_name']['size']
登录后复制

是否大于零;

推荐:《最新的10个thinkphp视频教程

php入门到就业线上直播课:立即学习
全程直播 + 实战授课 + 边学 + 边练 + 边辅导

以上就是详解ThinkPHP怎么实现图片上传的详细内容,更多请关注php中文网其它相关文章!

回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}