html:
<!--批量上传-->
<input type="file" id="leading_in" class="hide">
<!--上传进度条-->
<div class="upfile_progress hide">
<div>
上传进度:<progress></progress>
</div>
<p id="progress">0 bytes</p>
<p id="info"></p>
</div>
css
progress{
background-color: #56BE64;
}
progress::-webkit-progress-bar { background: #ccc; }
progress::-webkit-progress-value { background: #56BE64; }
javascript:
// 导入文件
$('#leading_in').change(function(){
var exp = /.xls$|.xlsx$/;
if(exp.exec($(this).val())==null){
$(this).val('');//清空
layer.msg('格式错误',{icon: 2});
return false;
};
var data = new FormData();
data.append('file', $('#leading_in')[0].files[0]);
data.append('vote_id', $('input[name="vote_id"]').val());
var file = this.files[0]; //假设file标签没打开multiple属性,那么只取第一个文件就行了
name = file.name;
size = file.size;
type = file.type;
url = window.URL.createObjectURL(file); //获取本地文件的url,如果是图片文件,可用于预览图片
$.ajax({
url: 'index.php?c=Vote&a=importExcel',
type: 'post',
data: data,
cache: false,
contentType: false, //不可缺
processData: false, //不可缺
crossDomain: true,
xhrFields: {withCredentials: true},
dataType: 'json',
beforeSend: function(){
},
xhr: function(){ //获取ajaxSettings中的xhr对象,为它的upload属性绑定progress事件的处理函数
myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ //检查upload属性是否存在
//绑定progress事件的回调函数
myXhr.upload.addEventListener('progress',progressHandlingFunction, false);
}
return myXhr; //xhr对象返回给jQuery使用
},
success: function(res) {
if (res.code == 200) {
layer.msg('上传成功', {icon :1});
setTimeout(function(){
location.reload();
},1000);
}else{
layer.msg(res.msg, {icon: 2});
}
},
});
});
//上传进度回调函数:
function progressHandlingFunction(e) {
if (e.lengthComputable) {
$('progress').attr({value : e.loaded, max : e.total}); //更新数据到进度条
var percent = e.loaded/e.total*100;
$('#progress').html(((e.loaded/1024)/1024).toFixed(2) + "/" + ((e.total/1024)/1024).toFixed(2)+" MB. " + percent.toFixed(2) + "%");
}
}