einstein
einstein

Reputation: 13850

Client-side checking of a file input have a correct image file format

I wonder if there is a way of checking correct fileformat and size of an image using javascript?

I have a signup form and it is mandatory to upload an image before using the application:

<form action='signUp.php' method POST>
    choose your image: <input type='file'></input>
</form>

Upvotes: 1

Views: 501

Answers (1)

musicinmyhead
musicinmyhead

Reputation: 1476

You won't be able to check the file size with just javascript, but you should be able to check the file format of the file selected by simply grabbing the value of that input field and grabbing the last part. Like so, say you have this tag in your HTML:

<input type="file" id="afile" />

In your javascript you could have a function like this, and refer to it when the form is submitted:

function check_filetype(){
    var filename = document.getElementById('afile').value;
    return filename.substr(filename.lastIndexOf('.'));
}

Upvotes: 1

Related Questions