html 导入文件

html
首先用div展示导入按钮
<div class="uploadbtn"><span class="upchar" onclick="inputFile()">批量导入</span></div>
设置一个隐藏域,用来导入文件
<input type="file" name="file" id="userImport" style="display: none" onchange="uploadFiles();">
css
.uploadbtn{
    float: right;
    padding:3px;
    border-radius: 5px;
    height: 30px;
    border: 1px solid #169BD5;
    width: 80px;
    margin-right: 20px;
    background-color: #169BD5;
    display: inline-block;
    cursor: pointer;
}
.upchar{
    font-size: 14px;
    color: #fff;
    display: block;
    text-align: center;
}
js
在点击导入按钮之后,触发隐藏域的点击事件
function inputFile(){
    // 导入模板
    $('#userImport').click();
}
// 导入模板后上传附件
当隐藏域input获取焦点后,触发onchange事件
function uploadFiles(){
    判断文件是否为空
    if($('#userImport')[0].files.length==0){return}
    var file = new FormData();
     
    file.append('file', $('#userImport')[0].files[0]);
    //加载层  在文件上传中出现
    var load_cover =layer.load(0, {
        shade: [0.3,'#fff']
    });
    console.log(file);
    $.ajax({
        url: baseurl+'/project/projectUpload',
        type: 'POST',
        cache: false,
        data: file,
        processData: false,
        contentType: false
    }).done(function(res) {
        if(res.code==0){
            alert(res.msg);
            // layer.alert(res.message);
            //刷新
            jQuery("#list2").trigger("reloadGrid");
        }else{
            alert(res.msg);
        } 
        ajax执行完成,即文件上传文成,关闭加载层
        layer.close(load_cover);
        //console.log(res);
    }).fail(function(res) {
    ajax执行完成,即文件上传文成,关闭加载层
       layer.close(load_cover);
        layer.alert(res.message);
    });
}

猜你喜欢

转载自www.cnblogs.com/xy-milu/p/9479961.html
今日推荐