2017-03-16 98 views
0

我使用jquery ajax上傳帶有進度條的視頻和圖像文件。我使用服務器端表單驗證並檢查重複條目。我的問題是進度條變得完整後顯示驗證錯誤消息。我想是這樣的......jquery文件上傳進度條

if form validation is correct 
    then show progress bar 
else if form validation is not correct 
    then only show error message of form validation 
else if duplicate entry 
    then only show error message of duplicate entry 

這是我的js代碼:

$.ajax({ 
    url:   ajaxUrl, 
    type:  'POST', 
    dataType: 'json', 
    processData: false, 
    contentType: false, 
    async:  true, 
    data: formData, 
    xhr: function() { 
     //upload Progress 
     var xhr = $.ajaxSettings.xhr(); 

     if (xhr.upload) { 
      xhr.upload.addEventListener('progress', function (event) { 
       var percent = 0; 
       var position = event.loaded || event.position; 
       var total = event.total; 

       if (event.lengthComputable) { 
        percent = Math.ceil(position/total * 100); 
       } 
       var temp = event.loaded/event.total*100; 

       //update progressbar 
       $('div#upload-progress').text(percent + "%"); 
       $('div#upload-progress').css("width", + temp + "%"); 

      }, true); 
     } 
     return xhr; 
    }, 
    complete: function(xhr) { 
     if(xhr.responseText) { 
      //console.log(xhr); 
     } 
    }, 
    success: function(data, status){ 
     if (data.hasOwnProperty('form-error')) { 
      $.each(data['form-error'], function (key, value) { 
       $("span#span_" + key).text(value); 
      }) 
     } else { 
      // Form validation is correct 
     }    
    }, 
    error : function(xhr, textStatus, errorThrown) { 
     var data = xhr.responseText; 
     myWindow = window.open("data:text/html," + encodeURIComponent(data), "parent", "width=1000, height=600"); 
     myWindow.focus();  
    } 
}); 

誰能給我任何建議,如何做到這一點?

回答

1

如果您使用服務器來驗證文件,這意味着您必須首先上傳該文件,然後才能驗證該文件,因此您首先看到了進度欄。如果你只是想重複檢查(基於文件名,大小等),則需要2個Ajax請求:

  1. 僅發送文件名&大小和驗證。

  2. 如果有效,請上傳文件。 (當然再次驗證)

只是我的2美分。