views:

21318

answers:

17

I am using <input type="file" id="fileUpload" runat="server"> to upload a file in an ASP.NET application. I would like to limit the file type of the upload (example: limit to .xls or .xlsx file extensions).

Both JavaScript or server-side validation are OK (as long as the server side validation would take place before the files are being uploaded - there could be some very large files uploaded, so any validation needs to take place before the actual files are uploaded).

+1  A: 

Well - you won't be able to do it server-side on post-back as the file will get submitted (uploaded) during the post-back.

I think you may be able to do it on the client using JavaScript. Personally, I use a third party component called radUpload by Telerik. It has a good client-side and server-side API, and it provides a progress bar for big file uploads.

I'm sure there are open source solutions available, too.

Chris Roberts
+3  A: 

Check file extension of FileUpload control using Javascript

Gulzar
A: 

Your only option seems to be client-side validation, because server side means the file was already uploaded. Also the MIME type is usually dictated by the file extension.

use a JavaScript Framework like jQuery to overload the onsubmit event of the form. Then check the extension. This will limit most attempts. However if a person changes an image to extension XLS then you will have a problem.

I don't know if this is an option for you, but you have more client side control when using something like Silverlight or Flash to upload. You may consider using one of these technologies for your upload process.

Nick Berardi
+4  A: 

From javascript, you should be able to get the filename in the onsubmit handler. So in your case, you should do something like:

<form onsubmit="if (document.getElementById('fileUpload').value.match(/xls$/) || document.getElementById('fileUpload').value.match(/xlsx$/)) { alert ('Bad file type') ; return false; } else { return true; }">...</form>
stak
A: 

ASP.NET Upload FAQ

rohancragg
A: 

You could use a regular expression validator on the upload control:

  <asp:RegularExpressionValidator id="FileUpLoadValidator" runat="server" ErrorMessage="Upload Excel files only." ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.xls|.XLS|.xlsx|.XLSX)$" ControlToValidate="fileUpload"> </asp:RegularExpressionValidator>

There is also the accept attribute of the input tag:

<input type="file" accept="application/msexcel" id="fileUpload" runat="server">

but I did not have much success when I tried this (with FF3 and IE7)

AlexWilson
A: 

I think there are different ways to do this. Since im not familiar with asp i can only give you some hints to check for a specific filetype:

1) the safe way: get more informations about the header of the filetype you wish to pass. parse the uploaded file and compare the headers

2) the quick way: split the name of the file into two pieces -> name of the file and the ending of the file. check out the ending of the file and compare it to the filetype you want to allow to be uploaded

hope it helps :)

DeeCee
+7  A: 

Seems like you are going to have limited options since you want the check to occur before the upload. I think the best you are going to get is to use javascript to validate the extension of the file. You could build a hash of valid extensions and then look to see if the extension of the file being uploaded existed in the hash.

HTML:

<input type="file" name="FILENAME"  size="20" onchange="check_extension(this.value,"upload");"/>
<input type="submit" id="upload" name="upload" value="Attach" disabled="disabled" />

Javascript:

var hash = {
  'xls'  : 1,
  'xlsx' : 1,
};

function check_extension(filename,submitId) {
      var re = /\..+$/;
      var ext = filename.match(re);
      var submitEl = document.getElementById(submitId);
      if (hash[ext]) {
        submitEl.disabled = false;
        return true;
      } else {
        alert("Invalid filename, please select another file");
        submitEl.disabled = true;

        return false;
      }
}
Jamie
don't forget, this is only Client Side validation. I can still 'manually' HTTP-POST to the form url to bypass this check - you'll need to do a server side validation check also.
Pure.Krome
@jamie how to check for `.doc` and `.docx` word documents...
Pandiya Chendur
Just add those extension to the variable "hash". var hash = { 'xls' : 1, 'xlsx' : 1, 'doc' : 1, 'docx' : 1 };
Jamie
+1  A: 

Avoid the standard Asp.Net control and use the NeadUpload component from Brettle Development: http://www.brettle.com/neatupload

Faster, easier to use, no worrying about the maxRequestLength parameter in config files and very easy to integrate.

massimogentilini
A: 

As some people have mentioned, Javascript is the way to go. Bear in mind that the "validation" here is only by file extension, it won't validate that the file is a real excel spreadsheet!

Jonathan Arkell
+2  A: 

I agree with Chris, checking the extension is not validation of the type of file any way you look at it. Telerik's radUpload is probably your best option, it provides a ContentType property of the file being uploaded, which you can compare to known mime types. You should check for:

application/vnd.ms-excel,

application/excel,

application/x-msexcel

and for the new 2k7 format:

application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet

Telerik used to sell radUpload as an individual component, but now its wrapped into the controls suite, which makes it a little more expensive, but by far its the easiest way to check for the true type

RandomNoob
A: 

Ensure that you always check for the file extension in server-side to ensure that no one can upload a malicious file such as .aspx, .asp etc.

dr. evil
A: 

"^(([a-zA-Z]:)|(\{2}\w+)\$?)(\(\w[\w].*))(.xls|.XLS|.xlsx|.XLSX)$"

I am apply this validation expression but they doesn't response .pls I need to right advice pls send me as soon as possible.

annu
A: 

As an alternative option, could you use the "accept" attribute of HTML File Input which defines which MIME types are acceptable.

Definition here

chillysapien
A: 

It's pretty simple using regulare expression validator.

<asp:RegularExpressionValidator
id=”RegularExpressionValidator1″
runat=”server”
ErrorMessage=”Only zip file is allowed!”
ValidationExpression =”^.+(.zip|.ZIP)$”
ControlToValidate=”FileUpload1″
> </asp:RegularExpressionValidator>

Client-Side Validation of File Types Permissible to Upload

shailesh
A: 

The RegularExpressionValidator did the trick, after that you check the revUpload isvalid attribute, if it is, you can proceed to the upload. Well done. The accept= method seems to have no effect. Also, if you use a postback trigger, you can even stick the file control in an updatepanel.

guideX