2014-11-05 25 views
0

我在爲插件JQuery-File-upload而努力。Jquery文件上傳,分兩步啓動上傳

我想分兩步上傳過程。

  1. 第一步 - 當輸入[類型=文件]中選擇了一個文件,我想 要測試的類型和它的大小。唯一被接受的文件應該是 圖像文件,大小爲< 4MB。
    • 如果文件與這些約束不匹配,彈出窗口會顯示一條錯誤消息。
    • 如果文件是確定我在輸入顯示的文件名[類型=文本]
  2. 第二步 - 當上了「OK」按鈕,用戶點擊後, 文件上傳開始

我有以下代碼

$('#file-img').fileupload({ 
     dataType: 'json', 
     autoUpload: false, 
     formData: {type: 'businessPicture'}, 
     add: function (e, data) { 
      var uploadErrors = []; 
      var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i; 
      if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) { 
       uploadErrors.push('Not an accepted file type'); 
      } 
      if(data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 4000000) { 
       uploadErrors.push('File size is too big'); 
      } 
      if(uploadErrors.length > 0) { 
       alert(uploadErrors.join("\n")); 
      } else { 
       $.each(data.files, function (index, file) { 
        $("#txt-file-img").val(file.name); 
       }); 
        //I COMMENT THIS LINE because if I do not, the upload start here. 
       //data.submit(); 
      } 
     }, 
     done: function (e, data) { 
      $("#output").html('<p class="valid">SUCCESS!</p>'); 
      $.each(data.result.files, function (index, file) { 
       $("#preview-picture").css("max-width","160px"); 
       $("#preview-picture").css("max-height","150px"); 
       $("#preview-picture").attr("src",file.url+'#'+ new Date().getTime()); 
      }); 
     }, 
     progressall: function (e, data) { 
      var progress = parseInt(data.loaded/data.total * 100, 10); 
      $('#upload-progress .bar').css(
       'width', 
       progress + '%' 
      ).text(
       progress + '%' 
      ); 
     }, 
     fail: function (e, data) { 
      $("#output").html('<p class="error">FAIL!</p>'); 
     } 
    }); 
}); 

我不明白,大多數提供的插件網站上的例子。 使用上面的代碼,控件(大小爲&類型)都可以,但是我不知道如何在點擊按鈕後纔開始上傳。

根據你什麼是管理這種行爲的最佳方式?

非常感謝

回答

0

確定這是很容易。我只需要將按鈕上的click事件綁定到實例$('#file-img')。fileupload()的事件添加直接下的動作data.submit。

$('#file-img').fileupload({ 
    dataType: 'json', 
    autoUpload: false, 
    formData: {type: 'businessPicture'}, 
    add: function (e, data) { 
     var uploadErrors = []; 
     var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i; 
     if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) { 
      uploadErrors.push('Not an accepted file type'); 
     } 
     if(data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 4000000) { 
      uploadErrors.push('File size is too big'); 
     } 
     if(uploadErrors.length > 0) { 
      alert(uploadErrors.join("\n")); 
     } else { 
      $.each(data.files, function (index, file) { 
       $("#txt-file-img").val(file.name); 
      }); 
      $("#btn_add_valid").on('click',function() { 
       data.submit(); 
      }); 
     } 
    }, 
    //The rest of the function....