For any client side action we have to choose a scripting language to build our logic. Let us go for JavaScript. When use a file control we have to use a button control for doing the uploading action. It is better to refer to Anand’s article CodeSnip: Working with FileUpload Control to get the basic idea of using FileUpload control.
Then at the button Client event we have to add some JavaScript action to do the filtering action. We have to use the “OnClientClick” event of a <asp:Button /> control. The code is given below.
Listing 2: OnClientClick
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Upload"
Width="64px" OnClientClick="return CheckForTestFile();" />
Now our objective is to put the filtering logic in CheckForTestFile() JavaScript function. For this action, copy and paste the following code inside your <HEAD> tag of aspx page.
Listing 3: JS Filter function
<script language="javascript">
//Trim the input text
function Trim(input)
{
var lre = /^s*/;
var rre = /s*$/;
input = input.replace(lre, "");
input = input.replace(rre, "");
return input;
}
// filter the files before Uploading for text file only
function CheckForTestFile()
{
var file = document.getElementById('<%=fileDocument.ClientID%>');
var fileName=file.value;
//Checking for file browsed or not
if (Trim(fileName) =='' )
{
alert("Please select a file to upload!!!");
file.focus();
return false;
}
//Setting the extension array for diff. type of text files
var extArray = new Array(".txt", ".doc", ".rtf", ".pdf", ".sxw", ".odt",
".stw", ".html", ".htm", ".sdw", ".vor");
//getting the file name
while (fileName.indexOf("") != -1)
fileName = fileName.slice(fileName.indexOf("") + 1);
//Getting the file extension
var ext = fileName.slice(fileName.indexOf(".")).toLowerCase();
//matching extension with our given extensions.
for (var i = 0; i < extArray.length; i++)
{
if (extArray[i] == ext)
{
return true;
}
}
alert("Please only upload files that end in types: "
+ (extArray.join(" ")) + "nPlease select a new "
+ "file to upload and submit again.");
file.focus();
return false;
}
</script>
Let us go through the codes. The Trim() function would trim the input text. Therefore, in the above code we first check whether there is any file selected in FileUpload control or not. Then we parse the file name with the path to the file-name of the input file using the slice() method of JavaScript which takes the index as input. After getting the file we will still continue parsing to get the file extension out from the File name. Then we iterate a loop to match the input extension with the defeat extensions of our interest stored in an array. If the input extension does not match with any one of the given extension,s we show the alert message and return false as status. This does not allow us to Upload the file and give us a alert message to fetch a file with the given extensions.
reference : http://aspalliance.com/1614_Adding_Filter_Action_to_FileUpload_Control_of_ASPNET_20.1