skip to Main Content

i need help in checking file size before uploading file,

i want to check the size of file and then continue to upload

  $("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>

2

Answers


  1. You need to get the files from the file input object whereas your current code is trying to get them from this which refers to the entire form.

    $("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>
    Login or Signup to reply.
  2. # 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")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search