2017-03-16 109 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美分。