[html] Limit file format when using <input type="file">?

I'd like to restrict the type of file that can be chosen from the native OS file chooser when the user clicks the Browse button in the <input type="file"> element in HTML. I have a feeling it's impossible, but I'd like to know if there is a solution. I'd like to keep solely to HTML and JavaScript; no Flash please.

This question is related to html file types

The answer is


You can use "accept" attribute as a filter in the file select box. Using "accept" help you filter input files base on their "suffix" or their "meme type"

1.Filter based on suffix: Here "accept" attribute just allow to select files with .jpeg extension.

<input type="file" accept=".jpeg" />

2.Filter based on "file type" Here "accept" attribute just allow to select file with "image/jpeg" type.

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

Important: We can change or delete the extension of a file, without changing the meme type. For example it is possible to have a file without extension, but the type of this file can be "image/jpeg". So this file can not pass the accept=".jpeg" filter. but it can pass accept="image/jpeg".

3.We can use * to select all kind of a file type. For example below code allow to select all kind of images. for example "image/png" or "image/jpeg" or ... . All of them are allowed.

<input type="file" accept="image/*" /> 

4.We can use cama ( , ) as an "or operator" in select attribute. For example to allow all kind of images or pdf files we can use this code:

<input type="file" accept="image/* , application/pdf" />

I may suggest following:

  • If you have to make user select any of image files by default, the use accept="image/*"

    <input type="file" accept="image/*" />

  • if you want to restrict to specific image types then use accept="image/bmp, image/jpeg, image/png"

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

  • if you want to restrict to specific types then use accept=".bmp, .doc, .pdf"

    <input type="file" accept=".bmp, .doc, .pdf" />

  • You cannot restrict user to change file filer to all files, so always validate file type in script and server


There is the accept attribute for the input tag. However, it is not reliable in any way. Browsers most likely treat it as a "suggestion", meaning the user will, depending on the file manager as well, have a pre-selection that only displays the desired types. They can still choose "all files" and upload any file they want.

For example:

_x000D_
_x000D_
<form>_x000D_
    <input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Read more in the HTML5 spec

Keep in mind that it is only to be used as a "help" for the user to find the right files. Every user can send any request he/she wants to your server. You always have to validated everything server-side.

So the answer is: no you cannot restrict, but you can set a pre-selection but you cannot rely on it.

Alternatively or additionally you can do something similar by checking the filename (value of the input field) with JavaScript, but this is nonsense because it provides no protection and also does not ease the selection for the user. It only potentially tricks a webmaster into thinking he/she is protected and opens a security hole. It can be a pain in the ass for users that have alternative file extensions (for example jpeg instead of jpg), uppercase, or no file extensions whatsoever (as is common on Linux systems).


Technically you can specify the accept attribute (alternative in html5) on the input element, but it's not properly supported.


As mentioned in previous answers we cannot restrict user to select files for only given file formats. But it's really handy to use the accept tag on file attribute in html.

As for validation, we have to do it at the server side. We can also do it at client side in js but its not a foolproof solution. We must validate at server side.

For these requirements I really prefer struts2 Java web application development framework. With its built-in file upload feature, uploading files to struts2 based web apps is a piece of cake. Just mention the file formats that we would like to accept in our application and all the rest is taken care of by the core of framework itself. You can check it out at struts official site.


Yes, you are right. It's impossible with HTML. User will be able to pick whatever file he/she wants.

You could write a piece of JavaScript code to avoid submitting a file based on its extension. But keep in mind that this by no means will prevent a malicious user to submit any file he/she really wants to.

Something like:

function beforeSubmit()
{
    var fname = document.getElementById("ifile").value;
    // check if fname has the desired extension
    if (fname hasDesiredExtension) {
        return true;
    } else {
        return false;
    }
}

HTML code:

<form method="post" onsubmit="return beforeSubmit();">
    <input type="file" id="ifile" name="ifile"/>
</form>

Use input tag with accept attribute

<input type="file" name="my-image" id="image" accept="image/gif, image/jpeg, image/png" />

Click here for the latest browser compatibility table

Live demo here

To select only image files, you can use this accept="image/*"

<input type="file" name="my-image" id="image" accept="image/*" />

Live demo here

Only gif, jpg and png will be shown, screen grab from Chrome version 44 Only gif, jpg and png will be shown, screen grab from Chrome version 44


I know this is a bit late.

function Validatebodypanelbumper(theForm)
{
   var regexp;
   var extension =     theForm.FileUpload.value.substr(theForm.FileUpload1.value.lastIndexOf('.'));
   if ((extension.toLowerCase() != ".gif") &&
       (extension.toLowerCase() != ".jpg") &&
       (extension != ""))
   {
      alert("The \"FileUpload\" field contains an unapproved filename.");
      theForm.FileUpload1.focus();
      return false;
   }
   return true;
}

You can use the change event to monitor what the user selects and notify them at that point that the file is not acceptable. It does not limit the actual list of files displayed, but it is the closest you can do client-side, besides the poorly supported accept attribute.

_x000D_
_x000D_
var file = document.getElementById('someId');_x000D_
_x000D_
file.onchange = function(e) {_x000D_
  var ext = this.value.match(/\.([^\.]+)$/)[1];_x000D_
  switch (ext) {_x000D_
    case 'jpg':_x000D_
    case 'bmp':_x000D_
    case 'png':_x000D_
    case 'tif':_x000D_
      alert('Allowed');_x000D_
      break;_x000D_
    default:_x000D_
      alert('Not allowed');_x000D_
      this.value = '';_x000D_
  }_x000D_
};
_x000D_
<input type="file" id="someId" />
_x000D_
_x000D_
_x000D_

JSFiddle


You could actually do it with javascript but remember js is client side, so you would actually be "warning users" what type of files they can upload, if you want to AVOID (restrict or limit as you said) certain type of files you MUST do it server side.

Look at this basic tut if you would like to get started with server side validation. For the whole tutorial visit this page.

Good luck!


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to types

Cannot invoke an expression whose type lacks a call signature How to declare a Fixed length Array in TypeScript Typescript input onchange event.target.value Error: Cannot invoke an expression whose type lacks a call signature Class constructor type in typescript? What is dtype('O'), in pandas? YAML equivalent of array of objects in JSON Converting std::__cxx11::string to std::string Append a tuple to a list - what's the difference between two ways? How to check if type is Boolean