这篇文章主要介绍了Thinkphp框架+Layui如何实现图片/文件上传功能,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
本文实例讲述了Thinkphp框架+Layui实现图片/文件上传功能。分享给大家供大家参考,具体如下:
在项目中用到了,再网上找了现成的代码都是借口异常或者非法上传,所以在一番摸索搞定之后拿来和大家分享。
html:
<form class="layui-form layui-form-pane" action="" 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" > <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 >上传失败</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框架+Layui如何实现图片/文件上传功能”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。