0

Hi I made an Ajax upload form and it can handle multiple files.

I use XMLHttpRequest(); to send the request but what I'm really trying to do is to make the form send one file at a time (send the first file then wait to upload.php response then send the next file);

I have been trying this but didn't work:

function _(el){
return document.getElementById(el);
}

function uploadFile(){
var file = _("file").files;
var formdata= new FormData();
var ajax;
for(var i=0;i<file.length;i++){
formdata.append("file[]",file[i]);
ajax= new XMLHttpRequest();
ajax.upload.addEventListener("progress",progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler,false);
ajax.open("POST","Upload.php");
ajax.send(formdata);
}

}  
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;    
var percent= (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploading... please wait";
}

function completeHandler(event){
_("status").innerHTML = event.target.responseText;  
_("progressBar").value = 0;

}

If any one can help?

4

1 回答 1

0

如果您在循环中运行它,则循环不会等待任何异步操作。我认为,更好的方法是拥有某种堆栈,在这个堆栈中你将拥有你的文件。比你必须创建一个方法,它在调用时只发送一个文件。为了更好地理解,请参见下面的示例:

var files;

function _(el) {
    return document.getElementById(el);
}

function uploadFiles() {
    files = _("file").files;
    sendFile();                        // start sending files
}

function sendFile() {
    // checking, that there is any file to upload yet
    if (files.lenght == 0) {
        completeHandler();
        return true;                   //  upload is complete, you don't want to continue this method any more
    }

    var index = (files.length - 1);    // current file
    var file = files[index];           // sending only one file per call - the last item of files variable
    var formdata= new FormData();

    formdata.append("file[]",file);    // inserting current file
    files.splice(index, 1);            // don't forget to remove current file from the stack, otherwise you'll get an infinite loop

    var ajax = new XMLHttpRequest();

    ajax.upload.addEventListener("progress",progressHandler, false);
    ajax.addEventListener("load", sendFile, false);      // on complete call this method again to send another file
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler,false);
    ajax.open("POST","Upload.php");
    ajax.send(formdata);

    return true;                       // on send return true as a success (not so important)
}

其他处理程序方法将是原始的。

于 2013-09-22T13:32:45.487 回答