Ric Tokyo
Ric Tokyo

Reputation: 6575

How to filter which files can be seen on upload dialog box?

In an ASP.NET MVC application which is not to have client side objects like ActiveXes, Flash or Java Applets (JavaScript is OK), is it feasible to imagine it being possible that when an upload file dialog box pops up, it will only show the files I specify?

For example, only files of extension .docx or docx and jpg would be visible and selectable on the open-file-like dialog box for selecting a file to upload..

I have read that there is an issue with browser support for this functionality, although it is something that should work with the right settings?

If I could get some examples and some heads up on this, it would be great.

Would the AjaxControlKit be something that would support this functionality?

Thanks,

Ric

Upvotes: 0

Views: 3582

Answers (2)

Martin Cordova
Martin Cordova

Reputation: 21

The input element supports an accept attribute which is supported by modern browsers like Chrome:

<input id="file" type="file" name="file" size="30" 
accept="image/jpg,image/png,image/jpeg,image/gif">

Sadly this is not supported by IE, not even IE9.

Regards, Martin Cordova www.martincordova.com Dinamica - Java EE/Ajax/SQL framework with Eclipse based webapp generators.

Upvotes: 2

G-Wiz
G-Wiz

Reputation: 7426

You can't filter what files appear in the file upload dialog. This is browser-dependent and no browsers provide this functionality.

However, once the file has been selected, it's value can be checked using JavaScript. You can handle the submit event of a form element and match the file input's value with a regular expression. Here's some untested sample code:

<script type="text/javascript">
  function check(event)
  {
    if (!document.getElementById('file').value.match(/.*\.jpg/))
    {
      alert('File must have .jpg extension. Please try again.');
      return false;
    }
    return true;
  }
</script>

<form action="page.html" onsubmit="check">
  <input type="file" name="file" id="file"/>
</form>

Upvotes: 2

Related Questions