jquery 正在检查文件大小限制

2uluyalo  于 2023-03-01  发布在  jQuery
关注(0)|答案(2)|浏览(162)

我需要在上载文件前检查文件大小的帮助,
我想检查文件大小然后继续上载

$("form#data").submit(function(e) {
        e.preventDefault();   
        if(this.files[0].size > 2097152){
           alert("File is too big!");
           this.value = "";
           return false;
        };  
        var formData = new FormData(this);
    
        $.ajax({
            url: window.location.pathname,
            type: 'POST',
            data: formData,
            success: function (data) {
                alert(data)
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
    
    
    <form id="data" method="post" enctype="multipart/form-data">
        <input name="image" type="file" />
        <button>Submit</button>
    </form>
6kkfgxo0

6kkfgxo01#

您需要从文件输入对象获取文件,而当前代码试图从this获取文件,this引用整个表单。

$("form#data").submit(function(e) {
  e.preventDefault();
  const file_input = $(this).find('input[name="image"]')[0];
  console.log(file_input.files[0].size);
  if (file_input.files[0].size > 2097152) {
    alert("File is too big!");
    this.value = "";
    return false;
  };

  console.log("safe to upload...");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="data" method="post" enctype="multipart/form-data">
  <input name="image" type="file" />
  <button>Submit</button>
</form>
ryoqjall

ryoqjall2#

# import module
import os
# assign size
size = 0.0
# assign folder path
Folderpath = '/content/drive/MyDrive/models'

# get size
    for name in os.listdir(Folderpath):
    if os.path.isfile(os.path.join(Folderpath, name)):
    size = os.path.getsize(os.path.join(Folderpath, name))
    print(name,"{0:.2f}".format((size/1000000000)),"GB")

相关问题