2014-03-25 42 views
0

這有點複雜:我有一個帶有文件輸入字段和下面的上傳按鈕的表單。通過點擊該上傳按鈕,會觸發一個函數來執行ajax調用,以檢查名稱相同的文件是否已經位於上傳目錄中。如果該文件不存在「start_upload」 - 函數被觸發:如何通過點擊功能停止while循環?

function start_upload(){ 
    while(start < SIZE) { //start and end is 0 and ~200Bytes - that's the size of the parts of the file 
     i++; 
     upload(blob.slice(start, end), i, name, SIZE); 
     start = end; 
     end = start + BYTES_PER_CHUNK; 
    } 
} 

上傳功能如下:

function upload(blobOrFile, part, name, size) { 
    var formdata = new FormData(); 
    var xhr = new XMLHttpRequest(); 
    formdata.append('blob', blobOrFile); 
    formdata.append('part', part); 
    formdata.append('filename', name); 
    xhr.open('POST', 'upload2.php', true); 
    xhr.onload = function (e) { 
     uploaders.pop(); 
     if (!uploaders.length) { 
      //some code that's fired when upload has finished 
     } 
    }; 
    //some other irrelevant functions 
    uploaders.push(xhr); 
    xhr.send(formdata); 

} 

一切工作正常,但由於實用性的原因,我想創造一個取消上傳按鈕。我試過如下:

這個取消功能會停止所有當前的「POST」 - 請求,但是會從零開始重新開始。

$("#cancel").click(function(){ 
    xhr.abort(); 
}); 

$(document).ajaxStop(function() { 
    //do something after all ajax requests are finished or aborted 
}); 

任何想法如何我可以中止永久上傳?

回答

1

您可以使用一個標誌值用於此目的如下:

int flag=0; 
    function start_upload(){ 
    while(start < SIZE && flag==0) { //start and end is 0 and ~200Bytes - that's the size of the parts of the file 
     i++; 
     upload(blob.slice(start, end), i, name, SIZE); 
     start = end; 
     end = start + BYTES_PER_CHUNK; 
    } 
} 

而且你的取消按鈕將是:

$("#cancel").click(function(){ 
flag=1; 

});

希望它能爲你工作。

+0

是啊謝謝! :)那麼,我不得不使用兩個#cancel點擊功能,它終於按預期工作,但現在它都很好。兩個函數因爲一個外部函數改變了全局標誌變量的外部上傳函數(使用函數裏面的上傳函數將始終返回0)而另一個#cancel函數裏面的上傳函數使用xhr.abort();因爲xhr函數的外部是未定義的。 – user2718671

+0

永遠歡迎:) –