[Download Code]
Now you should see something along the lines of the following when viewing the page in your browser:
The code behind is as follows:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
namespace FileUpload
{
/// <summary>
/// Summary description for FileUpload.
/// </summary>
public class FileUpload : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label uploadLblMessage;
protected System.Web.UI.WebControls.Button cmdUploadFile;
protected System.Web.UI.WebControls.Label FileUploadTexLabel;
protected System.Web.UI.HtmlControls.HtmlInputFile FileToUpload;
string strFileDirectory = "C:\\temp\\";
private void Page_Load(object sender, System.EventArgs e)
{
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cmdUploadFile.Click += new System.EventHandler(this.cmdUpload_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void DeleteExistingFile (string strFileName)
{
if (strFileName.Trim().Length > 0)
{
FileInfo fileToDelete = new FileInfo(strFileName);
//if file exists then we will delete it
if (fileToDelete.Exists)
{
fileToDelete.Delete();
}
}
}
private void cmdUpload_Click(object sender, System.EventArgs e)
{
//determine file name to be uploaded
string strFileName = System.IO.Path.GetFileName(FileToUpload.PostedFile.FileName);
if (( FileToUpload.PostedFile != null) && (FileToUpload.PostedFile.ContentLength > 0))
{
try
{
//Save File to the server
FileToUpload.PostedFile.SaveAs(strFileDirectory + strFileName);
uploadLblMessage.Visible = true;
uploadLblMessage.Text = "File: " + strFileDirectory + strFileName + " Uploaded Successfully";
}
catch(Exception ex)
{
uploadLblMessage.Visible = true;
uploadLblMessage.Text = ex.Message;
DeleteExistingFile(strFileDirectory + strFileName);
}
}
else
{
uploadLblMessage.Text = "Select a file to upload. Please Try Again!";
}
}
}
}
When you attempt to upload a file you will be notified if the upload was a success or failure. Here is an example:
You could of course expand on this and limit the file size of uploads, creating unique directories to hold uploads for any given user, and sending out notification via email when a new upload occurs. I hope this example finds a use during you development process.