Sinan
Sinan

Reputation: 5980

How to specify list of files in HTML form?

When you use a <input type="file"> in your application you get the file select dialog box with all files as default.

Is there a way to specify file types for that? Is it possible for example to select ".txt" files only?

Upvotes: 1

Views: 441

Answers (3)

Ibu
Ibu

Reputation: 43840

on your validation you can check the file type or you can use the on change event to determine the file type.

<input name='upload' id='file' type='file' />

Javascript part

var file = document.getElementById('file');

if (file.value.test(/(\.txt)|(\.jpg)/gi)) { // case insensitive
  // then validate
}

in this case only txt or jpg will be accepted. but of course you will have to revalidate on the server side because javascript can easily be bypassed

Upvotes: 1

Matty
Matty

Reputation: 34523

Yes, with the accept attribute.

Any ol' garbage can be posted regardless of what you put in the HTML form so make sure to validate that the correct file type has been posted server-side.

Upvotes: 0

tjarratt
tjarratt

Reputation: 1690

This is really simple. All you do is add an accept attribute that defines what file extensions you'd like to allow.

<input type="file" accept="image/gif,image/jpeg">

That input would allow only gif and jpegs, but you can allow any comma separated list.

See: http://www.cs.tut.fi/~jkorpela/forms/file.html#filter http://www.w3schools.com/tags/att_input_accept.asp

edit: sure, you can do this with javascript too, by checking the filetype after selecting a file, but wouldn't you rather check before the user selects a file?

Upvotes: 3

Related Questions