Sometimes the client needs to upload files to the server or into a database like photos or Word documents or PDF and so on. So for that you need to check the extension of the file.
The following are some of the basic files with their extension.
To prevent this kind of problem, you need to validate the file on the client side as well as the server side. To learn more about that see the following.
Add a new "Website" named "Website1".
And you will get the default page named "Default.aspx".
Add a File upload control named "FileUpload1" and button with "Upload" text on the page.
Client Side: This is how to add the validation on the client side. Add the JavaScript code into the <script> tag as in the following:
- function GetExt()
- {
- var str = document.getElementById('FileUpload1').value;
- var ext = str.substring(str.length - 3, str.length).toString();
- extext = ext.toLowerCase();
- if (ext == "pdf")
- {
- alert("valid File")
- return true;
- }
- else
- {
- alert("Invalid File"); return false;
- }
- }
Call the function on the client click event of button.
- OnClientClick="return GetExt();"
Result
- If I select the PDF file then:
And click on the upload button, it will show to me that it's a valid file.
- If I select the text file
And click on the upload button, it will show to me that it's an invalid file.
Server Side: This is how to add validation on the server side.
Note: I will explain it after removing the preceding JavaScript code from the page.
Add the server code on the click event of the button.
- protected void Button1_Click(object sender, EventArgs e)
- {
- string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
- string extension = Path.GetExtension(filename);
- string contentType = FileUpload1.PostedFile.ContentType;
- HttpPostedFile file = FileUpload1.PostedFile;
- byte[] document = new byte[file.ContentLength];
- file.InputStream.Read(document, 0, file.ContentLength);
-
- if (extension != ".pdf")
- {
-
- Response.Write("This is Invalid Extension File");
- return;
- }
- else
- {
-
- Response.Write("This is valid File");
- }
- }
Now if I run the page it will look like:
Case 1: In this case I will upload a .png file which is an invalid file.
And the output will be "Invalid Extension file".
Case 2: In this case I will upload a valid PDF file.
And the output will be "Valid file".