簡體   English   中英

jQuery:在表單中動態添加文件上傳字段並驗證總大小

[英]jQuery: Dynamically add file upload fields in form and validate total size

是否可以使用jQuery計算/驗證/限制動態添加的文件字段的總上傳大小? 表單將以電子郵件副本的形式發送內容,因此應將上傳的總大小限制為例如。 20MB左右。 后端驗證沒有問題(通過PHP)。

驗證可以“即時”完成,也可以在提交時完成。

考慮以下代碼:

<div class="input_fields_wrap">
  <a href="#" class="add_field_button">+ Add</a>
  <div>
    <input type="file" name="attachment[]">
  </div>
</div>

和jQuery:

$(document).ready(function() {
  var max_fields = 10;
  var wrapper = $(".input_fields_wrap");
  var add_button = $(".add_field_button");

  var x = 1;
  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append('<div><input type="file" name="attachment[]"/><a href="#" class="remove_field">Remove</a></div>');
    }
  });

  $(wrapper).on("click", ".remove_field", function(e) {
    e.preventDefault();
    $(this).parent('div').remove();
    x--;
  })
});

小提琴: https : //jsfiddle.net/yyqnwfb9/1/

任何有關如何解決此問題的意見將不勝感激。

更新:帶有實施解決方案的新提琴: https : //jsfiddle.net/yyqnwfb9/2/

您可以使用HTML5 File API來獲取大小。 例如,要獲取頁面中所有文件的總大小(以字節為單位):

 function getTotal() { var total = 0; $(':file').each(function() { if (this.files && this.files[0]) { total += this.files[0].size; } }); return total; } $(function() { var maxSize = 3 * 1000 * 1000 ; // ~3MB $(document).on('change', ':file', function() { if (getTotal() > maxSize) { // Clear field $(this).val(''); // Display error? $('#total').append(' Too big'); } else { // Update total $('#total').text(getTotal()); } }); }); 
 input { display: block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="file" name="attachment[]"> <input type="file" name="attachment[]"> <input type="file" name="attachment[]"> <input type="file" name="attachment[]"> <input type="file" name="attachment[]"> <strong>Total Bytes: <span id="total">0</span></strong> 

我在上傳功能中設置了3MB的文件大小限制

 $(document).ready(function() { var max_fields = 10; var wrapper = $(".input_fields_wrap"); var add_button = $(".add_field_button"); var x = 1; var uploadField = document.getElementById("file"); uploadField.onchange = function() { if(this.files[0].size > 307200){ alert("File is too big!"); this.value = ""; } else{ $(add_button).click(function(e) { e.preventDefault(); if (x < max_fields) { x++; $(wrapper).append('<div><input type="file" name="attachment[]"/><a href="#" class="remove_field">Remove</a></div>'); } }); $(wrapper).on("click", ".remove_field", function(e) { e.preventDefault(); $(this).parent('div').remove(); x--; }) } }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="input_fields_wrap"> <a href="#" class="add_field_button">+ Add</a> <div> <input type="file" id="file" name="attachment[]"> </div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM