1. HTML代码
<div class="form-group required">
<label class="col-sm-3 control-label">文件名:</label>
<div class="col-sm-6">
<input id="fileName" name="fileName" class="form-control" type="text">
<div class="progress-div">
<span id="progress"></span>
</div>
</div>
<input id="file-btn" class="btn btn-warning" type="button" value="上传文件" onclick="$('input[id=rel_file]').click()">
</div>
.progress-div{
width: 100%;
height: 20px;
background-color: #ffffff;
}
#progress{
height: 20px;
background-color: #1d9e7d;
display: inline-block;
}
function save() {
$('#submitBtn').attr('disabled',true);
parent.layer.msg("正在上传,请稍后 ...");
var data = new FormData($('#DatumForm')[0]);
var url = irsCtxPath + "/biz/datumSave/upload";
doUpload(data, url, uploadSuccess, 'progress');
$('#submitBtn').attr('disabled',false);
}
// 上传成功后的回调函数
function uploadSuccess(data) {
if (data.code == 0) {
parent.layer.msg("操作成功");
parent.reLoad();
var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
parent.layer.close(index);
} else {
parent.layer.alert(data.msg);
}
}
// 上传
function doUpload(data, url, callBack, progressId) {
$.ajax({
url: url,
type: "POST",
data: data,
xhr: function(){ //获取ajaxSettings中的xhr对象,为它的upload属性绑定progress事件的处理函数
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ //检查upload属性是否存在
//绑定progress事件的回调函数
myXhr.upload.addEventListener('progress',function(e) {progressHandlingFunction(e, '#' + progressId)}, false);
}
return myXhr; //xhr对象返回给jQuery使用
},
success : function(data) {
callBack(data);
},
processData:false,
contentType:false
});
}
//上传进度回调函数:
function progressHandlingFunction(e, progressId) {
if (e.lengthComputable) {
$(progressId).attr({value : e.loaded, max : e.total}); //更新数据到进度条
var percent = e.loaded/e.total*100;
if (percent < 100) {
$(progressId).html(" 正在努力上传中,已完成 " + percent.toFixed(2) + "%");
} else {
$(progressId).html(" 已完成 ");
}
$(progressId).css('width', percent.toFixed(2) + "%");
}
}