.Net → ASP.Net – Uploading File To Server
August 4th, 2009 by Ryan Alford
Here is a small snippet of code that will allow visitors to your website to upload files to your server.
This code will open an OpenFileDialog box to allow the user to select a file.
<asp:TableCell>
Select File:
<input id="uplTheFile" type="file" runat="server" style="width: 476px; height: 26px" />
</asp:TableCell>
This code will add a button to the form to upload the file.
<asp:TableCell>
<asp:Button ID="cmdUploadFile" value="Upload" runat="server" Text="Upload" OnClick="cmdUploadFile_Click" />
</asp:TableCell>
cmdUploadFile_Click Event
protected void cmdUploadFile_Click(object sender, EventArgs e)
{
string strFileNameOnServer = uplTheFile.PostedFile.FileName;
string appDataPath = HttpContext.Current.Server.MapPath("~/App_Data");
if (string.IsNullOrEmpty(strFileNameOnServer))
{
lblInformation.Text = "Error - a file name must be specified.";
return;
}
if (uplTheFile.PostedFile != null)
{
try
{
uplTheFile.PostedFile.SaveAs(appDataPath + "\\" + strFileNameOnServer);
}
catch (Exception ex)
{
lblInformation.Text = "Error saving <b>" + strFileNameOnServer + "</b><br>. " + ex.Message;
}
}
}
This will upload the file into the App_Data folder of the website.
Tags: ASP.Net, Uploading Files
August 4th, 2009 at 2:00 PM
Good Content. Post more!
November 17th, 2011 at 2:01 PM
Semmi bajom a cikk, de nem értek egyet néhány pontot néhány extenct. Én valószínűleg egy kisebbségi, bár, lol. Köszönöm megosztására.