user979331
user979331

Reputation: 11941

HTML file input window limit size?

I am using input file and I am able to limit the file type in the file dialog window like so:

<input type="file" name="logoIMG" id="logoIMG" class="" accept=".png">

I am just wondering if I could limit the file size so the user can only pick files 2 MB or less?

Upvotes: 0

Views: 3293

Answers (4)

Sahal-Khasim
Sahal-Khasim

Reputation: 1

file upload size limit using javascript. const maxAllowedSize = 3 * 1024 * 1024; //this means max file size 3 mb

const doc_input = document.getElementById('file_upload')

doc_input.addEventListener('change', (event) => {
const target = event.target
    if (target.files && target.files[0]) {

    const maxAllowedSize = 3 * 1024 * 1024;
    if (target.files[0].size > maxAllowedSize) {
        alert('Choose max 3mb files');
        target.value = ''
    }
}
})
<input id="file_upload" type="file" />

Upvotes: 0

Eda Ozonal
Eda Ozonal

Reputation: 1

The min and max properties have the smallest and largest properties allowed for an element. min and max properties; Used with number, range, date, datetime, datetime-local, month, hour and week type.

Upvotes: -2

Kiran Mistry
Kiran Mistry

Reputation: 2725

You can't handle with HTML code u need to write some code for validation on file size limit

For Example :

var uploadField = document.getElementById("file");

uploadField.onchange = function() {
    if(this.files[0].size > 2097152){
       alert("File is too big!");
       this.value = "";
    };
};

This example should work fine. I set it up for roughly 2MB, 1MB in Bytes is 1,048,576 so you can multiply it by the limit you need.

Check or preview Here


You Can also go with JQuery like this

$("input[type='file']").on("change", function() {
  if (this.files[0].size > 2000000) {
    var size = this.files[0].size;
    size = ( size >>> 20 ) + '.' + ( size & (2*0x3FF ) ) + ' 𝐌𝐁 ' ;
    alert("Please upload file less than 𝟐𝐌𝐁 and your file size is " + size + " Thanks!! ");
    $(this).val('');
    return size;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
<input type="file">

Upvotes: 1

OgL0C
OgL0C

Reputation: 33

You can limit the size by using javascript but I don't think you can do it only using html.

There is a similar question on stack that you might find usefull : Limit the size of a file upload (html input element)

Upvotes: 0

Related Questions