亲宝软件园·资讯

展开

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

mencre 人气:0

本文实例讲述了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框架的PHP程序设计有所帮助。

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论