博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

asp.net 下载小文件

Posted on 2008-08-21 09:53  LonelyStar  阅读(219)  评论(0编辑  收藏  举报

 

 1private string fileName = string.Empty;
 2
 3        protected void Page_Load(object sender, EventArgs e)
 4        {
 5            if (!IsPostBack)
 6            {
 7                if (Request.QueryString["FileName"!= null)
 8                {
 9                    fileName = HttpUtility.UrlDecode(Request.QueryString["FileName"].ToString());
10                    DownLoad(fileName);
11                }

12            }

13        }

14
15
16
17        /// <summary>
18        /// Download file
19        /// </summary>
20        /// <param name="filePath">The file path.</param>

21        private void DownLoad(string filePath)
22        {
23            Response.Clear();
24            string fileName = Path.GetFileName(filePath);
25
26            FileStream fs = new FileStream(filePath, FileMode.Open);
27            byte[] bytes = new byte[(int)fs.Length];
28            fs.Read(bytes, 0, bytes.Length);
29            fs.Close();
30            Response.ContentType = "application/octet-stream";
31            Response.AddHeader("Content-Disposition""attachment; filename=" + HttpUtility.UrlDecode(fileName, System.Text.Encoding.UTF8));
32            Response.BinaryWrite(bytes);
33            Response.Flush();
34            Response.End();
35        }
 
Response.AddHeader("Content-Disposition""attachment; filename=" + HttpUtility.UrlDecode(fileName, System.Text.Encoding.UTF8));

 

下载的文件名出现乱码问题:

如果是文件名乱码,试试下面的:  
  string   httpHeader="attachment;filename="+HttpUtility.UrlEncode(strFileName+".xls");  
  Response.AppendHeader("Content-Disposition",   httpHeader);  
  如果是文件内容乱码,试试下面的:  
  Response.ContentEncoding=System.Text.Encoding.Default;  
  或  
  Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");