form表单文件上传

form表单文件上传

form表单文件上传的ajax方法与文本上传有一些不一样
首先form表单的enctype属性写为**“multipart/form-data”** 默认是application/x-www-form-urlencoded

<form class="layui-form" id="authorization-upload"  enctype="multipart/form-data" >
     <div class="layui-form-item layui-inline">
          <div class="layui-inline">
                <input type="file" name="file" required accept="image/jpeg"  lay-verify="required"  autocomplete="off" id="layui-upload" class="layui-input layui-upload">
                <button class=" layui-btn layui-authorupload-submit" lay-submit lay-filter="layui-authorupload-submit">上传</button>
         </div>
     </div>    
</form>

form.on('submit(layui-authorupload-submit)', function(data){
    var files = $('#layui-upload')[0].files //获取上传的文件列表
    var formData = new FormData(); //新建一个formData对象
    formData.append("file", files[0]); //append()方法添加字段
    var index = layer.confirm("确定上传吗?",{icon:3},function(){
      $.ajax({
        url:url,
        type:'post',
        data:formData,
        processData:false,//必填 必须false 才会避开jq对formdata的默认处理 XMLHttpRequest才会对formdata进行正确处理  否则会报Illegal invocation错误
        contentType:false,//必填 必须false 才会加上正确的Content-Type
        success:function(res) {
          if(JSON.parse(res).code == 0 ) {
            layer.msg("上传成功",{icon:1,time:2000},function(){
              layer.closeAll()
            })
          }else {
            layer.alert(JSON.parse(res).msg, {icon: 0});
            layer.close(index)
          }
        }
      })
    })
    return false;
  })

你可能感兴趣的:(else)