FileUpload is very simple control allows user to select file and upload.
You can easily handle that with very little coding and ease. I have given the full code behind for this functionality.
First create a aspx page with 3 controls
FileUpload: rename it to FileUpload1
Label: rename it to lblMsg
Button: rename it to btnAdd
Copy this code in your code behind file inside the class declaration. As you can see we are simply calling theSaveUploadedFile() function to save the uploaded file. you can check for the particular extension within the function right now we are checking for only 3 extensions. You can change it in sAllowedExt string.
Here is the code behind stuff:
String UPLOAD_PATH = "";
int MAXSIZE = 5 * 1024 * 1024; // max 5 MB
String sAllowedExt = ",.doc,.pdf,.xls,"; // make sure whatever extension you enter, string ends with comma
protected void Page_Load(object sender, EventArgs e)
{
btnUpload.Attributes.Add("onclick", "return checkFile();");
UPLOAD_PATH = Server.MapPath("~/UploadedDocs") + "/";
}
private void setMsg(String sMsg)
{
lblMsg.Text = sMsg;
}
protected void btnAdd_Click(object sender, EventArgs e)
{
try
{
SaveUploadedFile();
}
catch (Exception ex)
{
//Response.Write("Error: " + ex.Message);
setMsg("File could not be uploaded successfully.");
}
}
private void SaveUploadedFile()
{
if (FileUpload1.HasFile)
{
String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
String validExt = ;
if (validExt.IndexOf("," + fileExtension + ",") != -1)
{
if (FileUpload1.FileBytes.Length <= MAXSIZE)
{
FileUpload1.PostedFile.SaveAs(UPLOAD_PATH + FileUpload1.FileName);
setMsg("File uploaded successfully.");
}
else
{
setMsg("File size exceeded the permitted limit.");
}
}
else
{
setMsg("This file type is not accepted.");
}
}
}
Once the user uploads the file, it's availabe using FileUpload.PostedFile.SaveAs() method. You can then directly save that file to particular folder with new name. We are checking FileUpload1.HasFileto make sure we only process if a file is uploaded.
