JS-JQuery-使用input实现文件上传( type="file" )且有进度条(onprogress)

在另一篇里已经说了如何实现type="file"的input文件上传,现新增需求需要展示上传的进度,所以在原来基础上再加上

文件上传-不带进度条: https:////www.cnblogs.com/liangpi/p/12503533.html

先看效果展示:

 

1、首先还是先添加html

<!-- 上传按钮 -->
<div class="fileBtn" id="uploadBtn">
   <input type="file" id="uploadfile">
   <button type="button" class="btn btn-primary btn-sm btn-flie">上传附件</button>
</div>
<!-- 文件信息 -->
<div class="info-item" id="fileList">
   <!-- <div class="files-info">
     <p>文件1.pdf</p>
      <p class="filedown checkIcon"><img src="images/check.png" alt=""></p>
      <p class="filedown downIcon"><img src="images/down.png" alt=""></p>
      <p class="filedown deleteIcon"><img src="images/del.png" alt=""></p>
      </div> -->
</div>
<!-- 进度条 -->
<div class="progressBox" id="progressBox">
   <div class="progressItem">
       <div class="progressBar" id="progressBar"></div>
       <div class="progressText" id="progressText">0%</div>
   </div>
</div>

2、css样式

.fileBtn {
    position:relative;
}
.fileBtn #uploadfile {
    width: 120px;
    height: 30px;
    filter: Alpha(opacity=0);
    -moz-opacity:0;
    opacity: 0;
    position: absolute;
    z-index: 2;
}
.fileBtn .btn-flie {
    width: 120px;
    height: 30px;
    position: absolute; 
    z-index: 1;
}
.info-item {
    margin-top: 30px;
}
.progressBox{
    margin-top: 35px;
    width: 50%;
    height: 10px;
    background: #fff;
    display: block;
}
.progressBox .progressItem {
    width: 100%;
    height: 100%;
    border: 1px solid #ccc;
    border-radius: 5px;
    position: relative;
}
.progressBox .progressBar{
    width: 0;
    height: 100%;
    background: #337ab7;
    border-radius: 5px;
    position: absolute;
    top: 0;
    left: 0;
}
.progressBox .progressText{
    font-size: 14px;
    color: #337ab7;
    position: absolute;
    top: -7px;
    right: -50px;
}

3、js相关代码

var fileList = [] // 文件list
$('#uploadfile').change(function(){
    // 初始化进度条状态
    // $('#progressBox').css("display","block")
    $('#progressBar').css('width','0%');
    $('#progressText').text('0%');
    var fileItem = $('#uploadfile')[0].files[0]
    var formData = new FormData();
        formData.append('file', fileItem)
        formData.append('type', '1')
    $.ajax ({
        type : "post",
        url : "/user/upload",
        data : formData,
        async : true,
        cache : false,
        contentType : false,//需设置为false,因为是FormData对象,且已经声明了属性enctype="multipart/form-data"
        processData : false,//需设置为false,因为data值是FormData对象,不需要对数据做处理
        dataType : 'json',
        xhr: function() { 
            var xhr = $.ajaxSettings.xhr();
            if (xhr.upload) {
                xhr.upload.addEventListener("progress", function (e) {
                    var loaded = e.loaded; //已经上传大小情况
                    var tot = e.total; //附件总大小
                    var per = Math.floor(100 * loaded / tot); //已经上传的百分比
                    $('#progressBar').css('width',per+'%');   //这里指的是进度条的宽度等于完成的百分比
                    $('#progressText').text(per+'%'); //显示进度百分比
                }, false);
                return xhr;
            }
        },
        success : function (data) {
            if (data.code == 2000){
                var dataInfo = data.data
                if(dataInfo) {
                    toastr.success('上传成功'); // 提示上传成功插件-可以更换与不用
//                    $('#progressBox').css("display","none") // 这句是上传成功后将进度条隐藏,看自己需求是否需要
                               // 重置进度条
                               $('#progressBar').css('width','0%');
                               $('#progressText').text('0%');
                    setTimeout(
                       function(){ 
                           toastr.clear();
                    }, 1000);
                    fileList.push(dataInfo)
                    showFile()
                }
            } else{
                alert(data.message);
            }
        },
        error : function(data) {
            toastr.error('上传失败');
//            $('#progressBox').css("display","none")
            setTimeout(
               function(){ 
                   toastr.clear(); 
            }, 1000);
        }
    });
});

function showFile() {
        // 展示文件信息
    var fileItem = fileList
    if(fileItem.length){
        var str = ''
        for(var i = 0; i < fileItem.length; i++){
            str += '<div class="files-info"><div>';
            str +=  fileItem[i].name
            str += '</div>'
            str += '<div class="iconGroup">'
            str += '<p class="filedown downLoad"><img src="images/down.png" alt="" onclick=downFileItem('
            str += "\'";
            str += fileItem[i].url;
            str += "\'";    
            str += ')></p>';
            if(status!=1&&status!=3){
                str += '<p class="filedown delete"><img src="images/del.png" alt="" onclick=delFileItem('
                str += "\'";
                str += i;
                str += "\'";    
                str += ')></p>';
            }
            str += '</div>';
            str += '</div>';
        }
        $('#fileList').html(str)
    } else {
        $('#fileList').empty()
    }
};                    

 

posted @ 2020-03-20 14:15  涼皮Herr  阅读(2775)  评论(0编辑  收藏  举报