Popular Posts

Thursday, January 26, 2012

Download file inASP.Net



 public static void downloadFile(System.Web.UI.Page pg, string filepath)
    {
        pg.Response.AppendHeader("content-disposition", "attachment; filename=" + new FileInfo(filepath).Name);
        pg.Response.ContentType = getContentType(new FileInfo(filepath).Extension);
        pg.Response.WriteFile(filepath);
        pg.Response.End();
    }

Content type:
 public static string getContentType(string Fileext)
    {

        string contenttype = "";
        switch (Fileext)
        {
            case ".xls":
                contenttype = "application/vnd.ms-excel";
                break;
            case ".doc":
                contenttype = "application/msword";
                break;
            case ".ppt":
                contenttype = "application/vnd.ms-powerpoint";
                break;
            case ".pdf":
                contenttype = "application/pdf";
                break;
            case ".jpg":
            case ".jpeg":
                contenttype = "image/jpeg";
                break;
            case ".gif":
                contenttype = "image/gif";
                break;
            case ".ico":
                contenttype = "image/vnd.microsoft.icon";
                break;
            case ".zip":
                contenttype = "application/zip";
                break;
            default: contenttype = "";
                break;
        }
        return contenttype;
    }



calling:

        downloadFile(this.Page, Server.MapPath("~/images/image1.jpg"));

No comments:

Post a Comment