我正在尝试为我的应用程序中的上传进度制作进度条。到目前为止我有这个
JMeter
这是我的javascript
<div class="col-sm-12">
<span style="border-left:5px solid #555555; padding-left:.5em">Upload File</span>
<div style="margin-top:1em; margin-left:.8em;">
<input type="file" name="file" class="inputfile" id="group-agent-file" accept=".csv"/>
<label for="file" id="span-file-upload" class="btn btn-danger">
<span class="fa fa-upload" style="margin-right:.5em"></span>
<span id="span-file-name">Choose a file</span>
</label>
<div>
<button type="button" id="btn-group-agent-upload" class="btn btn-primary" title="Upload">Upload</button>
</div>
<div class="progress">
<div class="progress-bar progress-bar-green" role="progressbar" id="progress-bar-upload">
<span></span>
</div>
</div>
它工作正常,但我认为html处理不够,有时var result = event.target.result;
var data = $.csv.toObjects(result);
var length = data.length;
var count = 0;
var percent;
$.each(data, function (key, val) {
$.ajax({
xhr: function(){
var xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function (evt) {
console.log('progress', evt.loaded / evt.total * 100);
};
},
type: "POST",
url: "IROA_StoredProcedures.asmx/Insert_Bulk_Agent",
data: JSON.stringify(val),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
count = count + 1;
percent = count / length * 100;
$("#progress-bar-upload").css("width", percent + "%");
$("#progress-bar-upload span").text(percent + "% Complete");
console.log("Finished " + count + " of " + length + " employees.");
},
error: function (XMLHttpRequest) {
alert("error in Insert_Bulk_AgentInfo()");
console.log(XMLHttpRequest);
}
});
});
百分比被延迟。我怎样才能做到这一点?当我使用width
时可能会有什么缺点。
答案 0 :(得分:2)
要在jQuery中获取上传进度,您需要将事件监听器附加到进度事件。
你可以在jQuery中做这样的事情
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total);
//Update the progress bar
}
});
return xhr;
},
type: 'POST',
url: "/upload/path",
data: { YOUR UPLOAD DATA },
success: function (data) {
}
});
这对于普通的js
也是一样的var xhr = new XMLHttpRequest();
xhr.open('POST', "/upload/path", true);
xhr.upload.addEventListener('progress', function (event) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total);
//Update the progress bar
}
}
xhr.onload = function (response) {
// handle success/error here
}
xhr.setRequestHeader(SET_HEADERS);
xhr.send(UPLOAD_DATA);
答案 1 :(得分:2)
成功函数。 你应该使用xhr函数而不是成功。
contourf(X,Y,Z,v)
在另一个函数中更新进度条之后: -
xhr: function(){
var xhr = $.ajaxSettings.xhr() ;
xhr.upload.onprogress = function(evt){
console.log('progress', evt.loaded/evt.total*100);
var percentageCompleted = evt.loaded/evt.total*100;
updateUploadPercentage(parseInt(percentageCompleted));
if(percentageCompleted == 100){
$("#p_custom_message_body").html('<p>Storing training data</p><img src="media/images/loading.gif">');
}
} ;
return xhr ;
}