嗨,我实际上正在使用这个插件https://github.com/englercj/jquery-ajax-progress/
它只是在 ajax 请求中添加了一个 progress: 语句。
它工作得很好,我的代码如下所示:
var _min_width = 470;
var _min_height = 330;
var _which;
var _fyle_type;
var _file_name;
var allowed_types = new Array('image/png','image/jpg','image/jpeg');
if (typeof(FileReader) === 'function'){
$('input[type="file"]').on('change', function(e) {
_file_name = $(this).val();
var file = e.target.files[0];
if (!in_array(file.type,allowed_types) || file.length === 0){
notify("You must select a valid image file!",false,false);
return;
}
if(file.size > 3145728 /*3MB*/){
notify("<?php echo lang('each-photo-1MB'); ?>",false,false);
return;
}
notify_destroy();
var reader = new FileReader();
reader.onload = fileOnload;
reader.readAsDataURL(file);
});
function fileOnload(e) {
var img = document.createElement('img');
img.src = e.target.result;
img.addEventListener('load', function() {
if(img.width < _min_width || img.height < _min_height ){
notify("<?php echo lang('each-photo-1MB'); ?>",false,false);
return;
}
//remove not-needed base64 data:pfff
var clear_string = e.target.result.replace('data:image/jpeg;base64,','').replace('data:image/png;base64,','');
var _data;
if(_which == 'photo_1'){
_data = {photo_1:clear_string};
}if(_which == 'photo_2'){
_data = {photo_2:clear_string};
}if(_which == 'photo_3'){
_data = {photo_3:clear_string};
}if(_which == 'photo_4'){
_data = {photo_4:clear_string};
}
$.ajax({
type:'post',
dataType:'text',
data:_data,
url:_config_base_url+'/upload/upload_photos',
beforeSend:function(){
$('.'+_which+'_holder').fadeOut(0);
$('.'+_which+'_progress').fadeIn(0);
$('.'+_which+'_progress').addClass('progress-striped');
},
progress:function(e){
//make sure we can compute the length
if(e.lengthComputable) {
//calculate the percentage loaded
var pct = (e.loaded / e.total) * 100;
$('.'+_which+'_progress .bar').css({'width':pct+'%'});
$('.'+_which+'_progress .progress-opt span').text(pct.toFixed(0));
//console.log(pct);
}else {
console.warn('Content Length not reported!');
}
},
success:function(){
alert(_file_name+' uploaded ok');
},
complete:function(){
$('.'+_which+'_progress .progress-opt span').text('100');
$('.'+_which+'_holder p').text(_file_name);
$('.'+_which+'_progress .bar').css({'width':'100%'});
$('.'+_which+'_progress').delay(300).removeClass('progress-striped').fadeOut(0,function(){
$('.'+_which+'_holder').show(0);
$('.'+_which+'_progress .bar').css({'width':'0'});
});
}
});
});
}
}
现在的问题是,当我text(pct.toFixed(0))
在progress:
ajax 语句中设置时,我需要pct
“实时”,我的意思是,这段代码将请求进度以百分比表示,因此您可以看到请求结束所需的百分比。
问题是如果我启动这些请求中的 2 个,则 pct 会为两个请求共享,因此如果请求 1的进度为 40% (pct),那么请求 2 将从请求1继承相同的进度百分比(pct = 40%)