Andrej
Andrej

Reputation: 53

Limit file size upload in JavaScript

I am trying to limit the size on file when user is uploading. I am new to JavaScript so any help is welcome.This is what i am trying :

<input type="file" id="input_file" name="input_file" required maxlength="40" onchange="checkFileSize(this)" data-max_size="1048576" title="bla bla"

function checkFileSize(elem) {
var fsize = elem.files[0].size;
var fname = elem.files[0].name.length;
if (fsize > elem.getAttribute("data-max_size") || fname > elem.getAttribute("maxlength")) {
    elem.setCustomValidity(elem.getAttribute("title"));
} else {

    elem.setCustomValidity("");
}

}

When user uploads a file bigger than 1mb or there are more thn 40 characters in file name it doesnt fire title(bla bla), nothing happens. What i am doing wrong ?

Upvotes: 2

Views: 5315

Answers (3)

Sotiris Kiritsis
Sotiris Kiritsis

Reputation: 3346

You can use the File API.

Here is a working jsfiddle example. Code sample for validation:

function showFileSize() {
    var input, file;

    // (Can't use `typeof FileReader === "function"` because apparently
    // it comes back as "object" on some browsers. So just see if it's there
    // at all.)
    if (!window.FileReader) {
        bodyAppend("p", "The file API isn't supported on this browser yet.");
        return;
    }

    input = document.getElementById('fileinput');
    if (!input) {
        bodyAppend("p", "Um, couldn't find the fileinput element.");
    }
    else if (!input.files) {
        bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
    }
    else if (!input.files[0]) {
        bodyAppend("p", "Please select a file before clicking 'Load'");
    }
    else {
        file = input.files[0];
        // YOUR VALIDATION HERE USING file.size
        bodyAppend("p", "File " + file.name + " is " + file.size + " bytes in size");
    }
}

Keep in mind though, that client-side validation exists just to inform/guide the user and you should never rely on it for storing files in your server.

Upvotes: 2

Conor Cussell
Conor Cussell

Reputation: 161

I have put your code into JSBin - https://jsbin.com/rufigug/edit?html,js,console,output - it appears to be firing the correct IF block for me, perhaps you could console.log fname + fsize and check if your file does actually satisfy the conditions?

There is some good documentation for this on MDN https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation#Limiting_the_size_of_a_file_before_its_upload

Upvotes: 1

Nadir
Nadir

Reputation: 1819

You are using the event onchange . According to http://www.w3schools.com/jsref/event_onchange.asp, it is only for <select>.

Change onselect for oninput

Upvotes: 0

Related Questions