<p>I am using <code>&lt;input type="file" id="fileUpload" runat="server"&gt;</code> 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). </p>

<p>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).</p>

[{'answer_id': 71987, 'author': 'Chris Roberts', 'author_id': 475, 'author_profile': 'https://Stackoverflow.com/users/475', 'pm_score': 1, 'selected': False, 'text': '<p>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.</p>\n\n<p>I think you may be able to do it on the client using JavaScript.  Personally, I use a third party component called <a href="http://www.telerik.com/products/aspnet-ajax/controls/upload/overview.aspx" rel="nofollow noreferrer">radUpload by Telerik</a>.  It has a good client-side and server-side API, and it provides a progress bar for big file uploads.</p>\n\n<p>I\'m sure there are open source solutions available, too.</p>\n'}, {'answer_id': 72009, 'author': 'Nick Berardi', 'author_id': 17, 'author_profile': 'https://Stackoverflow.com/users/17', 'pm_score': 0, 'selected': False, 'text': "<p>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.  </p>\n\n<p>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.</p>\n\n<p>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.</p>\n"}, {'answer_id': 72013, 'author': 'staktrace', 'author_id': 12050, 'author_profile': 'https://Stackoverflow.com/users/12050', 'pm_score': 3, 'selected': False, 'text': '<p>From  javascript, you should be able to get the filename in the onsubmit handler. So in your case, you should do something like:</p>\n\n<pre><code>&lt;form onsubmit="if (document.getElementById(\'fileUpload\').value.match(/xls$/) || document.getElementById(\'fileUpload\').value.match(/xlsx$/)) { alert (\'Bad file type\') ; return false; } else { return true; }"&gt;...&lt;/form&gt;\n</code></pre>\n'}, {'answer_id': 72031, 'author': 'AlexWilson', 'author_id': 2240, 'author_profile': 'https://Stackoverflow.com/users/2240', 'pm_score': 2, 'selected': False, 'text': '<p>You could use a regular expression validator on the upload control:</p>\n\n<pre><code>  &lt;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"&gt; &lt;/asp:RegularExpressionValidator&gt;\n</code></pre>\n\n<p>There is also the accept attribute of the input tag:</p>\n\n<pre><code>&lt;input type="file" accept="application/msexcel" id="fileUpload" runat="server"&gt;\n</code></pre>\n\n<p>but I did not have much success when I tried this (with FF3 and IE7)</p>\n'}, {'answer_id': 72077, 'author': 'DeeCee', 'author_id': 5895, 'author_profile': 'https://Stackoverflow.com/users/5895', 'pm_score': 1, 'selected': False, 'text': '<p>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:</p>\n\n<p>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 </p>\n\n<p>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</p>\n\n<p>hope it helps :)</p>\n'}, {'answer_id': 72221, 'author': 'Jamie', 'author_id': 8391, 'author_profile': 'https://Stackoverflow.com/users/8391', 'pm_score': 6, 'selected': True, 'text': '<p>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.</p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;input type="file" name="FILENAME"  size="20" onchange="check_extension(this.value,"upload");"/&gt;\n&lt;input type="submit" id="upload" name="upload" value="Attach" disabled="disabled" /&gt;\n</code></pre>\n\n<p>Javascript:</p>\n\n<pre><code>var hash = {\n  \'xls\'  : 1,\n  \'xlsx\' : 1,\n};\n\nfunction check_extension(filename,submitId) {\n      var re = /\\..+$/;\n      var ext = filename.match(re);\n      var submitEl = document.getElementById(submitId);\n      if (hash[ext]) {\n        submitEl.disabled = false;\n        return true;\n      } else {\n        alert("Invalid filename, please select another file");\n        submitEl.disabled = true;\n\n        return false;\n      }\n}\n</code></pre>\n'}, {'answer_id': 72305, 'author': 'massimogentilini', 'author_id': 11673, 'author_profile': 'https://Stackoverflow.com/users/11673', 'pm_score': 1, 'selected': False, 'text': '<p>Avoid the standard Asp.Net control and use the NeadUpload component from Brettle Development: <a href="http://www.brettle.com/neatupload" rel="nofollow noreferrer">http://www.brettle.com/neatupload</a><br/>\n<br/>\nFaster, easier to use, no worrying about the maxRequestLength parameter in config files and very easy to integrate.</p>\n'}, {'answer_id': 72608, 'author': 'Jonathan Arkell', 'author_id': 11052, 'author_profile': 'https://Stackoverflow.com/users/11052', 'pm_score': 2, 'selected': False, 'text': '<p>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!</p>\n'}, {'answer_id': 72909, 'author': 'Ta01', 'author_id': 7280, 'author_profile': 'https://Stackoverflow.com/users/7280', 'pm_score': 3, 'selected': False, 'text': '<p>I agree with Chris, checking the extension is not validation of the type of file any way you look at it. <a href="http://www.telerik.com/products/aspnet-ajax/controls/upload/overview.aspx" rel="noreferrer">Telerik\'s radUpload</a> 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:</p>\n\n<p>application/vnd.ms-excel, </p>\n\n<p>application/excel, </p>\n\n<p>application/x-msexcel </p>\n\n<p>and for the new 2k7 format:</p>\n\n<p>application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet</p>\n\n<p>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</p>\n'}, {'answer_id': 330563, 'author': 'dr. evil', 'author_id': 40322, 'author_profile': 'https://Stackoverflow.com/users/40322', 'pm_score': 2, 'selected': False, 'text': '<p>Ensure that you always check for the file extension in server-side to ensure that no one can upload a <strong>malicious file</strong> such as .aspx, .asp etc.</p>\n'}, {'answer_id': 2287671, 'author': 'chillysapien', 'author_id': 30297, 'author_profile': 'https://Stackoverflow.com/users/30297', 'pm_score': 1, 'selected': False, 'text': '<p>As an alternative option, could you use the "accept" attribute of HTML File Input which defines which MIME types are acceptable.</p>\n\n<p>Definition <a href="http://www.w3schools.com/jsref/dom_obj_fileupload.asp" rel="nofollow noreferrer">here</a></p>\n'}, {'answer_id': 3188902, 'author': 'shailesh', 'author_id': 264813, 'author_profile': 'https://Stackoverflow.com/users/264813', 'pm_score': 5, 'selected': False, 'text': '<p>It\'s pretty simple using regulare expression validator.  </p>\n\n<pre><code>&lt;asp:RegularExpressionValidator\nid="RegularExpressionValidator1"\nrunat="server"\nErrorMessage="Only zip file is allowed!"\nValidationExpression ="^.+(.zip|.ZIP)$"\nControlToValidate="FileUpload1"\n&gt; &lt;/asp:RegularExpressionValidator&gt;\n</code></pre>\n\n<p><a href="http://patelshailesh.com/index.php/client-side-validation-of-file-types-permissible-to-upload" rel="noreferrer">Client-Side Validation of File Types Permissible to Upload</a></p>\n'}, {'answer_id': 17468608, 'author': 'm_cheung', 'author_id': 582032, 'author_profile': 'https://Stackoverflow.com/users/582032', 'pm_score': 2, 'selected': False, 'text': '<p>Based on kd7\'s reply suggesting you check for the files content type, here\'s a wrapper method:</p>\n\n<pre><code>private bool FileIsValid(FileUpload fileUpload)\n{\n    if (!fileUpload.HasFile)\n    {\n        return false;\n    }\n    if (fileUpload.PostedFile.ContentType == "application/vnd.ms-excel" ||\n        fileUpload.PostedFile.ContentType == "application/excel" ||\n        fileUpload.PostedFile.ContentType == "application/x-msexcel" ||\n        fileUpload.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" //this is xlsx format\n        )\n        return true;\n\n    return false;\n}\n</code></pre>\n\n<p>returning true if the file to upload is .xls or .xlsx</p>\n'}, {'answer_id': 19550823, 'author': 'Mark_fsg', 'author_id': 2864444, 'author_profile': 'https://Stackoverflow.com/users/2864444', 'pm_score': 0, 'selected': False, 'text': '<p>As another respondent notes, the file type can be spoofed (e.g., .exe renamed .pdf), which checking for the MIME type will not prevent (i.e., the .exe will show a MIME of "application/pdf" if renamed as .pdf). I believe a check of the true file type can only be done server side; an easy way to check it using System.IO.BinaryReader is described here:</p>\n\n<p><a href="http://forums.asp.net/post/2680667.aspx" rel="nofollow">http://forums.asp.net/post/2680667.aspx</a></p>\n\n<p>and VB version here: </p>\n\n<p><a href="http://forums.asp.net/post/2681036.aspx" rel="nofollow">http://forums.asp.net/post/2681036.aspx</a></p>\n\n<p>Note that you\'ll need to know the binary \'codes\' for the file type(s) you\'re checking for, but you can get them by implementing this solution and debugging the code.</p>\n'}, {'answer_id': 54115000, 'author': 'Rana', 'author_id': 1964270, 'author_profile': 'https://Stackoverflow.com/users/1964270', 'pm_score': 0, 'selected': False, 'text': '<p>Client Side Validation Checking:-</p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;asp:FileUpload ID="FileUpload1" runat="server" /&gt;\n&lt;asp:Button ID="btnUpload" runat="server" Text="Upload" OnClientClick = "return ValidateFile()"  OnClick="btnUpload_Click"  /&gt;\n&lt;br /&gt;\n&lt;asp:Label ID="Label1" runat="server" Text="" /&gt;\n</code></pre>\n\n<p>Javascript:</p>\n\n<pre><code>&lt;script type ="text/javascript"&gt;\n\n    var validFilesTypes=["bmp","gif","png","jpg","jpeg","doc","xls"];\n\n    function ValidateFile()\n\n    {\n\n      var file = document.getElementById("&lt;%=FileUpload1.ClientID%&gt;");\n\n      var label = document.getElementById("&lt;%=Label1.ClientID%&gt;");\n\n      var path = file.value;\n\n      var ext=path.substring(path.lastIndexOf(".")+1,path.length).toLowerCase();\n\n      var isValidFile = false;\n\n      for (var i=0; i&lt;validFilesTypes.length; i++)    \n      {    \n        if (ext==validFilesTypes[i])    \n        {    \n            isValidFile=true;    \n            break;    \n        }    \n      }\n\n      if (!isValidFile)    \n      {    \n        label.style.color="red";    \n        label.innerHTML="Invalid File. Please upload a File with" +    \n         " extension:\\n\\n"+validFilesTypes.join(", ");    \n      }    \n      return isValidFile;    \n     }    \n&lt;/script&gt;\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/71944', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51/']