本文实例讲述了Thinkphp框架+Layui实现图片/文件上传功能。分享给大家供大家参考,具体如下:
在项目中用到了,再网上找了现成的代码都是借口异常或者非法上传,所以在一番摸索搞定之后拿来和大家分享。
html:
<form class="layui-form layui-form-pane" action="" style="margin-top:20px;" enctype="multipart/form-data"> <center> <div class="layui-upload-drag" id="uploadBanner"> <img class="layui-upload-img" id="upload-photo"> <i class="layui-icon" id="upload-icon"></i> <p>点击上传,或将文件拖拽到此处</p> <p>建议尺寸1920*512</p> </div> <input type="hidden" id="res" name="banner_photo" value="" lay-verify="required" /> <div class="layui-form-item" style="margin-top:10px;"> <button class="layui-btn" lay-submit="" lay-filter="sub">提交</button> </div> <div id="demoText"></div> </center> </form>
JS:
layui.use('upload', function(){ var $ = layui.jquery ,upload = layui.upload; //普通图片上传 var uploadInst = upload.render({ elem: '#uploadBanner' ,url: "{:U('Api/doUploadPic')}" ,before: function(obj){ //预读本地文件示例,不支持ie8 obj.preview(function(index, file, result){ $('#upload-photo').attr('src', result); //图片链接(base64) $('#upload-photo').attr('style', 'height:10rem;'); $('#upload-icon').attr('style','display:none;'); }); } ,done: function(res, index, upload){ //如果上传失败 if(res.code > 0){ return layer.msg('上传失败'); } //上传成功 console.log("成功啦!" + obj2string(res) + " " + index + " " + upload); } ,error: function(){ //演示失败状态,并实现重传 var demoText = $('#demoText'); demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>'); demoText.find('.demo-reload').on('click', function(){ uploadInst.upload(); }); } }); });
PHP接口:
public function doUploadPic()//上传模块 { $upload = new \Think\Upload(); $upload->maxSize = 3145728; $upload->exts = array('jpg', 'gif', 'png', 'jpeg'); $upload->rootPath = './Public/'; // 设置附件上传根目录 $upload->savePath = 'upload/'; // 设置附件上传子目录 $info = $upload->upload(); if(!$info){ $this->error($upload->getError()); }else{ foreach($info as $file){ $data = '/Public'.$file['savepath'] . $file['savename']; $file_a=$data; echo '{"code":0,"msg":"成功上传","data":{"src":"'.$file_a.'"}}'; } } }
图片就上传到/Public/upload文件夹下了:
更多关于thinkPHP相关内容感兴趣的读者可查看本站专题:《ThinkPHP入门教程》、《thinkPHP模板操作技巧总结》、《ThinkPHP常用方法总结》、《codeigniter入门教程》、《CI(CodeIgniter)框架进阶教程》、《Zend FrameWork框架入门教程》及《PHP模板技术总结》。
希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
桃源资源网 Design By www.nqtax.com
暂无“Thinkphp框架+Layui实现图片/文件上传功能分析”评论...