katie ferr
katie ferr

Reputation: 23

Checking file size limit

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>

Upvotes: 0

Views: 339

Answers (2)

fabio alcantara
fabio alcantara

Reputation: 1

# 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")

Upvotes: 0

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

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>

Upvotes: 1

Related Questions