This article I will use to explain you how you can restrict
user to upload only .doc or .docx file in asp.net using c#.net. In this we will
do server side validation before uploading file.
Some of my previous articles are as follows: File
Upload in MVC3 By Using Razor, Multiple
File Upload With Asp.Net MVC C# and HTML5 | How to upload files to ASP.NET MVC
application, How
to Get the Full Path of FileUpload Control in Asp.Net, How
To Get File Size Uploaded By FileUpload Control Using C# In Asp.Net, File
Upload with ASP.NET | How to Use FileUpload Control in ASP.Net Using
C#.Net,VB.Net | Upload File in Asp.net and Save in Folder, File
Upload in C#.Net Windows Application.
So for this article first we will create a new asp.net
application. Now in page a we will add
fileupload control , button control and label control to display message. Here is
the html code.
<div>
<h2>
<asp:Label ID="lblmessage"
runat="server"
Style="color: #FF0000; font-size: small;"
Text=""></asp:Label>
</h2>
Upload File :<asp:FileUpload ID="FileUpload1" runat="server" />
(upload .doc,.docx)<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload" />
</div>
|
Now generate button control and add the below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace UploadFileinAsp.net
{
public partial class _Default : System.Web.UI.Page
{
protected
void Page_Load(object
sender, EventArgs e)
{
}
protected
void Button1_Click(object
sender, EventArgs e)
{
if
(FileUpload1.HasFile)
{
string
fileextention = System.IO.Path.GetExtension(FileUpload1.FileName);
if
(fileextention == ".doc" ||
fileextention == ".docx")
{
string
filename = System.IO.Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/document/"
+ filename));
lblmessage.Text = "File uploaded successfully.";
}
else
{
lblmessage.Text = "You are allowed to upload only .doc or .docx
file.";
}
}
}
}
}
|
In above code first we have find the extension of the file
and after that we are validating the file type. If file type in .doc or .docx
on that case we are allow to upload file otherwise we are displaying error
message.
Now run the page. First
we will select pdf file and click on upload. We will get error message.
Now select .pdf file
Now we will select word document and click on upload. We will get successful upload message.
Now select doc file
DOWNLOAD
0 comments:
Please let me know your view