1

I am using php for post submission handling, but here i want to restrict the image upload size to 20kb before form submission. Here i am trying to uploading 3 images one by one in different fields. Need help with this

Thank You

user.php

<input type="file" text-align="right" class="filestyle" name="p1" id="p1" data-size="sm" data-input="false" required/>
<input type="file" text-align="right" class="filestyle" name="p2" id="p2" data-size="sm" data-input="false" required/>
<input type="file" text-align="right" class="filestyle" name="p3" id="p3" data-size="sm" data-input="false" required/>

Script Here i am viewing the file size

$('#p1').bind('change', function() {
        alert('This file size is: ' + this.files[0].size/1024/1024 + "MB");
    });

How to restrict the size of the image before clicking submit button

sparkrish77
  • 27
  • 2
  • 5
  • your question answered on below link: http://stackoverflow.com/questions/1601455/how-to-check-file-input-size-with-jquery#answer-3937404 – Aiyoub A. Apr 23 '17 at 07:09

2 Answers2

4

File sizes can be compared from within the change event handler and if it exceeds the input is cleared. It can also be done on submit.

$('input#file').bind('change', function() {
  var maxSizeKB = 20; //Size in KB
  var maxSize = maxSizeKB * 1024; //File size is returned in Bytes
  if (this.files[0].size > maxSize) {
    $(this).val("");
    alert("Max size exceeded");
    return false;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="file" id="file">
Dan Philip Bejoy
  • 4,321
  • 1
  • 18
  • 33
0

You can use a <form> element as parent for each <input type="file"> element, include a <input type="submit"> element with disabled attribute set adjacent to each <input type="file"> element. If .files[0].size is less than 20000, set disabled of <input type="submit"> element to false, else set disabled attribute to true.

const SIZE = 20 * 1024;

$(".filestyle").on("change", function(e) {
  console.log(this.files[0].size);
  let VALID = false;
  if (this.files[0].size > SIZE) {
    this.value = "";
    console.log("file size greater than " + SIZE);
  } else {
    console.log("file size less than " + SIZE);
    VALID = true;  
  }
  $("+ input[type=submit]", this).prop("disabled", !VALID)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="file" text-align="right" class="filestyle" name="p1" id="p1" data-size="sm" data-input="false" required/><input type="submit" disabled/>
</form>
<form>
<input type="file" text-align="right" class="filestyle" name="p2" id="p2" data-size="sm" data-input="false" required/><input type="submit" disabled/>
</form>
<form>
<input type="file" text-align="right" class="filestyle" name="p3" id="p3" data-size="sm" data-input="false" required/><input type="submit"  disabled/>
</form>
guest271314
  • 1
  • 15
  • 104
  • 177