n this article i will show you how to upload a file using fileuploadcontrol using C# in asp.net. In this article i will show you some of the important functionality which we can perform wile uploading the file.
For uploading file first create a new web project. Add a new aspx page. After adding aspx page add a fileuploadcontrol, Button and a Label. After adding you html code of page will look as shown below:
<form id="form1" runat="server">
<div>
<h2>
Fileupload control in asp.net</h2>
</div>
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
</div>
<div>
<asp:Button ID="btnupload" runat="server" Text="Upload Your File"
onclick="btnupload_Click" />
</div>
<div>
<asp:Label ID="lblmessage" runat="server" Style="color: #FF0000; font-weight: 700"
Text=""></asp:Label>
</div>
</form>
Now create a new folder by "image".<div>
<h2>
Fileupload control in asp.net</h2>
</div>
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
</div>
<div>
<asp:Button ID="btnupload" runat="server" Text="Upload Your File"
onclick="btnupload_Click" />
</div>
<div>
<asp:Label ID="lblmessage" runat="server" Style="color: #FF0000; font-weight: 700"
Text=""></asp:Label>
</div>
</form>
Now by clicking on button control generate the click event of the button control. As you click on button on your .cs page you will get code as shows below
protected void btnupload_Click(object sender, EventArgs e)
{
}
{
}
Now we will write code to upload file:
protected void btnupload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = System.IO.Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/images/" + fileName));
lblmessage.Text = "File uploaded successfully.";
}
else
{
lblmessage.Text = "Please select file.";
}
}
In above code in first line we have checked weather user have selected any file or not if user have not selected any file then he will get the error message that "Please select file".Now if user select file in this first we will get the file name. After that we will file save the file name in image folder. In this we are not doing any special validation like file size,file extension, save file by user specified file name.{
if (FileUpload1.HasFile)
{
string fileName = System.IO.Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/images/" + fileName));
lblmessage.Text = "File uploaded successfully.";
}
else
{
lblmessage.Text = "Please select file.";
}
}
Now we will run the page . After running page we will get following screen:
Now without selecting click on button you will get error message.
Now select a file and click on button for uploading the file.
After successful upload following screen will come.
Now open your image folder which you have created. You will get the uploaded image.
No comments:
Post a Comment