Monday 12 August 2013

Download file inside Ajax UpdatePanel in ASP.NET


In this article I am going to show you how to download the file from UpdatePanel. 

1. Create new ASP.NET Web page in VisualStudio.

2. Before going to add UpdatePanel to your page you must add ScriptManager control to your web page. 

3. Drag and drop ScriptManager control on to the page.
 <ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </ajax:ToolkitScriptManager>

4. Now drag and drop UpdatePanel to the page.
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always">
            <ContentTemplate>              
            </ContentTemplate>           
</asp:UpdatePanel>

5.  Now add Button inside the UpdatePanel.
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always">
            <ContentTemplate>
                <asp:Button ID="btnDownloadFile" runat="server" Text="Download File" OnClick="btnDownloadFile_Click" />
            </ContentTemplate>           
</asp:UpdatePanel>

6. To download the file write the following code in button click event.

    protected void btnDownloadFile_Click(object sender, EventArgs e)
    {
        //Send physical path of the file
        DownloadFile("D:\\Test.txt");
    }
    private void DownloadFile(string filePath)
    {
        // Get the physical Path of the file
        string filepath = filePath;
        System.IOFileInfo file = new System.IOFileInfo(filepath);

        if (file.Exists)
        {
            Response.ClearContent();
            // Add the file name and attachment
            Response.AddHeader("Content-Disposition", "attachment; filename=Test.txt");
            // Add the file size into the response header
            Response.AddHeader("Content-Length", file.Length.ToString());
            // Set the ContentType
            Response.ContentType = GetFileExtension(file.Extension.ToLower());
            // Write the file into the response
            Response.TransmitFile(file.FullName);
            Response.End();
        }
    }
    private string GetFileExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/ms-word";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
            case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
    }

7. Now open the web page in browser and click on download file button. The file will not download because UpdatePanel is used for partial page rendering. If you want to download the file you should  postback whole page. To resolve this problem we need to rely upon a standard postback i.e. we need to set the button that is download file to be PostBack trigger. This will initiate a normal postback whenever we click the download file button and it is possible to download the file. So, add the postback trigger to the UpdatePanel as follows.
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always">
            <ContentTemplate>
                <asp:Button ID="btnDownloadFile" runat="server" Text="Download File" OnClick="btnDownloadFile_Click" />
            </ContentTemplate>
            <Triggers>
                <asp:PostBackTrigger ControlID="btnDownloadFile" />
            </Triggers>
        </asp:UpdatePanel>

8.  Now save and open the page in browser and click on download file button. Now you are able to download the file from the UpdatePanel.


Whole page script: 

<%@ Page Language="C#" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<!DOCTYPE html>
<html>
<script runat="server">
   
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnDownloadFile_Click(object sender, EventArgs e)
    {
        //Send physical path of the file
        DownloadFile("D:\\Test.txt");
    }
    private void DownloadFile(string filePath)
    {
        // Get the physical Path of the file
        string filepath = filePath;
        System.IOFileInfo file = new System.IOFileInfo(filepath);

        if (file.Exists)
        {
            Response.ClearContent();
            // Add the file name and attachment
            Response.AddHeader("Content-Disposition", "attachment; filename=Test.txt");
            // Add the file size into the response header
            Response.AddHeader("Content-Length", file.Length.ToString());
            // Set the ContentType
            Response.ContentType = GetFileExtension(file.Extension.ToLower());
            // Write the file into the response
            Response.TransmitFile(file.FullName);
            Response.End();
        }
    }
    private string GetFileExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/ms-word";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
            case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
    }
</script>
<body>
    <form id="form1" runat="server">
        <ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </ajax:ToolkitScriptManager>
        <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always">
            <ContentTemplate>
                <asp:Button ID="btnDownloadFile" runat="server" Text="Download File" OnClick="btnDownloadFile_Click" />
            </ContentTemplate>
            <Triggers>
                <asp:PostBackTrigger ControlID="btnDownloadFile" />
            </Triggers>
        </asp:UpdatePanel>
    </form>
</body>
</html>


No comments: