欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-10-30 18:41:52
本文实例讲述了thinkphp框架+layui实现图片/文件上传功能。分享给大家供大家参考,具体如下:在项目中用到了,再网上找了现成的代码都是借口异常或者非法上传,所以在一番摸索搞定之后拿来和大家分享...

本文实例讲述了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框架+Layui实现图片/文件上传功能分析

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