Thinkphp框架+Layui实现图片/文件上传功能分析

时间:2021-09-01 16:41:55

本文实例讲述了Thinkphp框架+Layui实现图片/文件上传功能。分享给大家供大家参考,具体如下:

在项目中用到了,再网上找了现成的代码都是借口异常或者非法上传,所以在一番摸索搞定之后拿来和大家分享。

html:

  1. <form class="layui-form layui-form-pane" action="" style="margin-top:20px;" enctype="multipart/form-data">
  2. <center>
  3. <div class="layui-upload-drag" id="uploadBanner">
  4. <img class="layui-upload-img" id="upload-photo">
  5. <i class="layui-icon" id="upload-icon"></i>
  6. <p>点击上传,或将文件拖拽到此处</p>
  7. <p>建议尺寸1920*512</p>
  8. </div>
  9. <input type="hidden" id="res" name="banner_photo" value="" lay-verify="required" />
  10. <div class="layui-form-item" style="margin-top:10px;">
  11. <button class="layui-btn" lay-submit="" lay-filter="sub">提交</button>
  12. </div>
  13. <div id="demoText"></div>
  14. </center>
  15. </form>

JS:

  1. layui.use('upload', function(){
  2. var $ = layui.jquery
  3. ,upload = layui.upload;
  4. //普通图片上传
  5. var uploadInst = upload.render({
  6. elem: '#uploadBanner'
  7. ,url: "{:U('Api/doUploadPic')}"
  8. ,before: function(obj){
  9. //预读本地文件示例,不支持ie8
  10. obj.preview(function(index, file, result){
  11. $('#upload-photo').attr('src', result); //图片链接(base64)
  12. $('#upload-photo').attr('style', 'height:10rem;');
  13. $('#upload-icon').attr('style','display:none;');
  14. });
  15. }
  16. ,done: function(res, index, upload){
  17. //如果上传失败
  18. if(res.code > 0){
  19. return layer.msg('上传失败');
  20. }
  21. //上传成功
  22. console.log("成功啦!" + obj2string(res) + " " + index + " " + upload);
  23. }
  24. ,error: function(){
  25. //演示失败状态,并实现重传
  26. var demoText = $('#demoText');
  27. demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
  28. demoText.find('.demo-reload').on('click', function(){
  29. uploadInst.upload();
  30. });
  31. }
  32. });
  33. });

PHP接口:

  1. public function doUploadPic()//上传模块
  2. {
  3. $upload = new \Think\Upload();
  4. $upload->maxSize = 3145728;
  5. $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
  6. $upload->rootPath = './Public/'; // 设置附件上传根目录
  7. $upload->savePath = 'upload/'; // 设置附件上传子目录
  8. $info = $upload->upload();
  9. if(!$info){
  10. $this->error($upload->getError());
  11. }else{
  12. foreach($info as $file){
  13. $data = '/Public'.$file['savepath'] . $file['savename'];
  14. $file_a=$data;
  15. echo '{"code":0,"msg":"成功上传","data":{"src":"'.$file_a.'"}}';
  16. }
  17. }
  18. }

图片就上传到/Public/upload文件夹下了:

Thinkphp框架+Layui实现图片/文件上传功能分析

Thinkphp框架+Layui实现图片/文件上传功能分析

希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。

原文链接:https://blog.csdn.net/qq_17497931/article/details/81290604