AsyncFileUpload - Upload file in existing directory
In this Code Snippet we are going to see how to use AsyncFileUpload control of AJAX. This code snippet uploads the file in a directory. It creates the directory if it does not exists and then saves the file, otherwise saves the file in existing directory
In this Code Snippet we are going to see how to use AsyncFileUpload control of AJAX. This code snippet uploads the file in a directory. It creates the directory if it does not exists and then saves the file, otherwise saves the file in existing directory.
Step1: Create an ASP.NET Web Application.
Step2: Drag and Drop a AsyncFileUpload and ScriptManager control in the Default.aspx page of the website as below:
<<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<cc1:AsyncFileUpload ID="AsyncFileUpload1" Width="400px" runat="server"
onuploadedcomplete="AsyncFileUpload1_UploadedComplete" />
Step3: In the Code-Behind file (Default.aspx.cs), Add the following code which uploads the file in a directory. It creates the directory if it doesnot exist.
protected void AsyncFileUpload1_UploadedComplete
(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
if (AsyncFileUpload1.HasFile)
{
string strPath = MapPath("~/Upload/") ;
string strFilePath = strPath + Path.GetFileName(e.FileName);
//Check if the Upload directory exists in the given path
bool dirExists = Directory.Exists(strPath);
//If the directory does not exist, Create it.
if (!dirExists)
Directory.CreateDirectory(MapPath("~/Upload/"));
//Save the uploaded file.
AsyncFileUpload1.SaveAs(strFilePath);
}
}