HTML代码

<form class="layui-form">
  <div class="layui-form-item">
    <label class="layui-form-label">尾灯名称</label>
    <div class="layui-input-block">
      <input type="text" name="name" required lay-verify="required" placeholder="请输入尾灯名称" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-input-block">
      <button type="button" class="layui-btn" id="upload">
        <i class="layui-icon">&#xe67c;</i>上传图标
      </button>
      <br><br>
      <div style="width:200px;height:200px;border:3px solid #0099CC;border-radius: 5px;padding: 3px;">
        <img style="max-width: 200px;max-height:200px;" id="preview">
      </div>
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-input-block">
      <button class="layui-btn" id="commit" onclick="return false">立即提交</button>
    </div>
  </div>
</form>

JavaScript代码

<script>
  layui.use(['form', 'layer', 'upload'], function () {
    var layer = layui.layer;
    var upload = layui.upload;
    var $ = layui.jquery;

    upload.render({
      elem: '#upload',
      url: '{:U("addTL")}',
      auto: false,//选择文件后不自动上传
      bindAction: '#commit',
      //上传前的回调
      before: function () {
        this.data = {
          name: $('input[name="name"]').val()
        }
      },
      //选择文件后的回调
      choose: function (obj) {
        obj.preview(function (index, file, result) {
          $('#preview').attr('src', result);
        })
      },
      //操作成功的回调
      done: function (res, index, upload) {
        var code = res.code === 0 ? 1 : 2;
        layer.alert(res.msg, {icon: code}, function () {
          parent.window.location.reload();
        })
      },
      //上传错误回调
      error: function (index, upload) {
        layer.alert('上传失败!' + index);
      }
    });
  })
</script>

以上这篇layui 实现表单和文件上传一起传到后台的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com