Friday, January 27, 2012

File upload control in ASP.Net with Ajax


.aspx file code

<div> 
  <fieldset>
    <legend>Upload Video</legend>

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <Triggers >
                <asp:PostBackTrigger ControlID ="bln_UploadVideo" />
            </Triggers>
            <ContentTemplate >
               <asp:FileUpload ID="FileUploadVideos" runat="server" />
               <asp:Button ID="bln_UploadVideo" runat="server" Text="Upload Video" onclick="bln_UploadVideo_Click" />
               <asp:Label ID="lblMessage" runat="server" ForeColor="#3366FF"></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>       
  </fieldset>
</div>

.cs code for single file upload code

   protected void bln_UploadVideo_Click(object sender, EventArgs e)
        {
            if (FileUploadVideos.HasFile)
            {
                try
                {
                    string filename = Path.GetFileName(FileUploadVideos.FileName);
                    string fileExtension = Path.GetExtension(filename);

                    if (fileExtension == ".wmv" || fileExtension == ".swf" || fileExtension == ".avi" || fileExtension == ".mp4" || fileExtension == ".mpeg"   || fileExtension == ".mpg" || fileExtension == ".qt")
                    {
                        FileUploadVideos.SaveAs(Server.MapPath(@"~/Upload/Video/") + filename);
                        lblMessage.Text = "File is uploaded!";
                    }
                    else{
                              FileUploadVideos.SaveAs(Server.MapPath(@"~/Upload/otherFile/")+ filename);
                    }
                }
                catch (Exception ex)
                {
                    lblMessage.Text = "The file could not be uploaded. The following error occured: " + ex.Message;
                }
            }
        }        


.cs file code for multiple file upload

 protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            // get HttpFileCollection
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0)
                {
                     hpf.SaveAs(Server.MapPath(@"~/Upload/Video/") + Path.GetFileName(hpf.FileName));
                    lblMessage.Text = "File is uploaded!";
                 }
            }
        }
        catch (Exception ex)
        {
            lblMessage.Text = "The file could not be uploaded. The following error occured: " + ex.Message;
        }

Thanks,
Anil

No comments: