/
0
FileUpload Control in ASP.NET
This article illustrates how to upload a file to server using FileUpload control. Here we are going to use one FileUpload control to select a file and one button control to upload the selected file to server.
Create a new website in VS and add the following code that designs our aspx page with FileUpload control and button. Add a folder to the solution and name it as “Uploaded Files” because we are going to use it to store the uploaded files.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="FileUpload_Example._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<b>FileUpload Control Example</b>
<br />
<table cellpadding="2">
<tr>
<td>
<asp:Label ID="lblMsg" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" /><asp:Button ID="btnUpload" runat="server"
Text="Upload" Width="100px" OnClick="btnUpload_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
And it’s code behind using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FileUpload_Example
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblMsg.Visible = false;
}
else
{
lblMsg.Visible = true;
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
//Check wheather FileUpload1 control has file or not
if (FileUpload1.HasFile)
{
//get the selected file name.
string filename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
//get the server path
string SaveLocation = Server.MapPath("~/Uploaded Files/") + filename;
//the following line saves the file to the server.
FileUpload1.PostedFile.SaveAs(SaveLocation);
lblMsg.Visible = true;
lblMsg.Text = "File upload Successful.";
lblMsg.ForeColor = System.Drawing.Color.Green;
}
else
{
lblMsg.Visible = true;
lblMsg.Text = "Please choose a file to upload.";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
}
catch (Exception ex)
{
string str = ex.Message;
lblMsg.Visible = true;
lblMsg.Text = "Unable to upload file.";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
}
}
}
Enjoy this article?
Tagged as:
ASP.NET,
FileUpload Control
0
comments
Comments (0)
Subscribe to:
Post Comments (Atom)
Translate
Labels
- ASP.NET (4)
- Cookies (1)
- FileUpload Control (1)
- Office 2010 Errors (1)
- Password Generator (1)
- SharePoint 2010 (4)
Followers
About Me
Powered by Blogger.

