Upload a file from my ASP.NET page?
To upload a file with your ASP.NET page, you need the use of two classes: System.Web.UI.HtmlControls.HtmlInputFile class and the System.Web.HttpPostedFile.
The HtmlInputFile class represents an HTML input control that the user will use on the client to select a file to upload.
The HttpPostedFile class represents the uploaded file. This is obtained from the .PostedFile property of the HtmlInputFile control.
In order to use the HtmlInputFile control, you need to add the enctype attribute to your form tag as follows:
<form id="upload" method="post" runat="server" enctype="multipart/form-data">
Below is a simple example of how to upload a file via an ASP.NET page using C#.
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.UI.HtmlControls" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Drawing" %>
<html>
<head>
<title>upload_cs</title>
</head>
<script language="C#" runat="server">
public void UploadFile(object sender, EventArgs e)
{
if (loFile.PostedFile != null)
{
try
{
String strFileName, strFileNamePath, strFileFolder;
strFileFolder = Context.Server.MapPath(@"data\");
strFileName = loFile.PostedFile.FileName;
strFileName = Path.GetFileName(strFileName);
strFileNamePath = strFileFolder + strFileName;
loFile.PostedFile.SaveAs(strFileNamePath);
lblFileName.Text = strFileName;
lblFileLength.Text = loFile.PostedFile.ContentLength.ToString();
lblFileType.Text = loFile.PostedFile.ContentType;
pnStatus.Visible = true;
}
catch (Exception x)
{
Label lblError = new Label();
lblError.ForeColor = Color.Red;
lblError.Text = "Exception occurred: " + x.Message;lblError.Visible = true;this.Controls.Add(lblError);
}
}
}
</script>
<body>
<form id="upload_cs" method="post" runat="server" enctype="multipart/form-data">
<P>
<INPUT type="file" id="loFile" runat="server">
</P>
<P>
<asp:Button id="btnUpload" runat="server" Text=" Upload " OnClick="UploadFile"></asp:Button>
</P>
<P>
<asp:Panel id="pnStatus" runat="server" Visible="False"><asp:Label id="lblFileName" Font-Bold="True" Runat="server"></asp:Label>
uploaded
<BR>
<asp:Label id="lblFileLength" Runat="server"></asp:Label> bytes
<BR>
<asp:Label id="lblFileType" Runat="server"></asp:Label>
</asp:Panel>
</P>
</form>
</body >
</html>
No comments:
Post a Comment