C#实现文件下载

  • 问题描述
     在Ext环境下无法使用传统的.net方式实现文件下载,要么点了下载按钮无反应要么出现乱码。
  • 原因分析
     由于EXT.NET在后台对前台进行操作,依赖的是Extjs,也就是它会向前台输送Javascript脚本代码,如果采用传统的页面内文件下载的方式就会向前台输送一个文件流,那么Extjs就无法正确的识别该文件流,最终导致文件无法下载。
  • 解决方案
     那么怎么才能在Ext环境下实现下载呢?其实很简单,不要在主页面内进行文件下载,而是调用另一个页面专门进行文件下载处理。
    • 主页面
      • 方法一(JS代码)
window.location.href="~/Service/DownLoad.aspx?filename="+ fileName +"&filepath="+ filePath;
      • 方法二(C#代码)
X.Redirect("~/Service/DownLoad.aspx?filename="+ fileName +"&filepath="+ filePath);
    • 下载功能页面
publicpartialclassService_DownLoad: System.Web.UI.Page
{
   protectedvoidPage_Load(objectsender,EventArgse)
    {
       stringfilename = Request.QueryString["filename"];
       stringfilepath = Request.QueryString["filepath"];
        DownloadFile(filename, filepath);
    }
 
   ///<summary>
   ///文件下载
   ///</summary>
   ///<param name="filename">文件名</param>
   ///<param name="filepath">文件路径 </param>
   protectedvoidDownloadFile(stringfilename,stringfilepath)
    {
        Response.Clear();
        Response.AddHeader("Content-Disposition","attachment; filename="+HttpUtility.UrlEncode(filename, System.Text.Encoding.Default));
        Response.ContentType ="application/octet-stream";
        Response.TransmitFile(filepath);
        Response.End();
    }
}
posted on 2014-05-22 17:34  记性特差  阅读(1482)  评论(0)    收藏  举报