我在这里看到过一些类似问题的帖子,但我似乎无法解决这个问题。基本上,我有一个AJAX文件上传器似乎没有调用progress事件。其他事件启动很好,文件上传完全符合我的预期,但是没有调用progress事件。 javascript如下所示:
$('input[name=avatar_upload]').change(function(e) {
// Get the Form
var setupForm = $('#setup-member-form');
// Get the File Array
var file = document.getElementById('avatar-upload').files[0];
// Show the File Upload Progress
$('#avatar-upload-progress').show();
// Create a new Form Data Object
var formData = new FormData();
// Add the File
formData.append('avatar', file);
// Create the AJAX Object
var ajax = new XMLHttpRequest();
// Add the Event Listeners
ajax.addEventListener("loadstart", function(evt) {
// Do something in here...
$('#output').append("upload starting...\n");
}, false);
ajax.addEventListener("progress", function(evt) {
var percentLoaded = (evt.loaded / evt.total) * 100;
$('#output').append(percentLoaded + "% loaded\n");
$('#avatar-upload-progress .ui-progress-bar-inner').animate({'width' : percentLoaded + '%'}, 400);
}, false);
ajax.addEventListener("load", function(evt) {
// Do something in here when loaded...
$('#output').append("upload complete!");
}, false);
// Open the Form
ajax.open("POST", $('input[name=upload_handler]').val());
ajax.send(formData);
});
起初我以为这可能只是因为文件太小而无法使进度事件有机会发射,但我已经尝试使用较大的文件,并且加载事件触发,然后有几秒钟暂停,然后整个事件开始。
如果有人有任何想法,请告诉我!
答案 0 :(得分:5)
刚刚对此进行了测试,对于上传,您必须使用XMLHttpRequest.upload
,因为直接将事件附加到XMLHttpRequest
只会在上传时触发一次。
$('#avatar-upload').on('change', function () {
var file = document.getElementById('avatar-upload').files[0];
$('#avatar-upload-progress').show();
var formData = new FormData();
formData.append('avatar', file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("loadstart", function (evt) {
$('#output').append("upload starting...\n");
}, false);
ajax.upload.addEventListener("progress", function (evt) {
var percentLoaded = (evt.loaded / evt.total) * 100;
$('#output').append(percentLoaded + "% loaded\n");
$('#avatar-upload-progress .ui-progress-bar-inner').animate({
'width': percentLoaded + '%'
}, 400);
}, false);
ajax.upload.addEventListener("load", function (evt) {
$('#output').append("upload complete!");
}, false);
ajax.open("POST", $('input[name=upload_handler]').val());
ajax.send(formData);
});