网站首页 » js,默认分类 » jq + ajax 按钮实现上传文件(代码)

jq + ajax 按钮实现上传文件(代码)

June 10, 2020 js,默认分类

按钮代码

<button type="button" title="上传附件" id="uploadFile" data-toggle="tooltip" class="btn btn-secondary"><i class="fa fa-cloud-upload"></i></button>

jQ代码

$("#uploadFile").click(function(){
    var post = '';//上传接口
    var field = 'file';//字段名
    var accept = '.jpg,.txt,.png';//字段类型
    var htmls='<input type="file" name="'+field+'" id="uploadFile_'+field+'" accept="'+accept+'"/> ';
    $('body').append(htmls);
    $("#uploadFile_"+field).click();
    //监听变化提交
    $("#uploadFile_"+field).on("input propertychange", function() {
      var formData = new FormData();
      formData.append(field,$("#uploadFile_"+field)[0].files[0]);
        formData.append("accept",accept);
        $("#uploadFile_"+field).remove();
        $.ajax({
            url:post,
            type:'post',
            data: formData,
            contentType: false,
            processData: false,
            success:function(res){                
                console.log(res.data);
                if(res.data["code"]=="succ"){
                    alert('成功');
                }else if(res.data["code"]=="err"){
                    alert('失败');
                }else{
                    console.log(res);
                }
            }
        })
    })
});

封装自定义函数,带回调

/*
*url 上传接口地址
*field 字段名
*accept 限制类型
*fun_success 成功回调函数 传入返回内容
*fun_error 错误回调函数 
*fun_before 请求前执行函数
*fun_end 请求完成执行函数
 */
function upload(upurl,field='file',accept='.jpg,.png',fun_success='',fun_error='',fun_before='',fun_end=''){
    var le = 'legend';
    var htmls='<input type="file" name="'+field+'" id="_'+le+'_uploadFile_'+field+'" accept="'+accept+'"/> ';
    $('body').append(htmls);
    $("#_"+le+"_uploadFile_"+field).click();
    //监听变化提交
    $("#_"+le+"_uploadFile_"+field).on("input propertychange", function() {
      var formData = new FormData();
      formData.append(field,$("#_"+le+"_uploadFile_"+field)[0].files[0]);
        formData.append("accept",accept);
        $("#_"+le+"_uploadFile_"+field).remove();
        $.ajax({
            url:upurl,
            type:'post',
            data: formData,
            contentType: false,
            processData: false,
            beforeSend: function(index){
                if (typeof fun_before === "function"){
                    fun_before(index);
                }
            },
            success:function(data){                
                if (typeof fun_success === "function"){
                    fun_success(data);
                }
            },
            complete:function(index,item){
                if (typeof fun_end === "function"){
                    fun_end(index,item);
                }
            },
            error: function(data) {
                if (typeof fun_error === "function"){
                    fun_error(data);
                }
        }
        });        
    });
}
Title - Artist
0:00