C# response输出要下载的文件流到客户端


在。。。.aspx.cs页面上
protected void Page_Load(object sender, EventArgs e){
 string fileData = (ViewData["branchViewData"] as Hashtable)["key"] as string;
 string[] strSplit = fileData.Split('-');
 byte[] bytes = new byte[strSplit.Length];
 for(int i = 0; i < strSplit.Length; i++){
  bytes[i] = byte.Parse(strSplit[i],System.Globalization.NumberStyles.AllowHexSpecifier);
  
 }
 // 清除缓存区流中的所有内容输出
 Response.Clear();
 // 设置缓冲输出为true,后台编辑的文件写到内存流中了
 Response.Buffer = true;
 // 设置编码格式 ContentEncoding是管字节流到文本的,而Charset是管在浏览器中显示的
 //Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
 Response.Charset = "UTF-8";
 // 将HTTP头添加到输出流,指定默认名
 Response.AddHeader("Content-Disposition", string.Format(@"attachment;filename=""{0}""",HttpUtility.UrlEncode("文件.et")));
 Response.ContentEncoding = System.Text.Encoding.UTF8;
 // 设置输出流的HTTP MIME类型为application/vnd.ms-excel
 Response.ContentType = "application/vnd.ms-excel";
 Response.AddHeader("Content-Length", bytes.Length.ToString());
 // 将指定的文件写入HTTP内容输出流
 Response.OutputStream.Write(bytes, 0, bytes.Length);
 //防止文件名含中文出现乱码而进行编码
 // Response.BinaryWrite(bytes);
 // 向客户端发送当前所有缓冲的输出
 Response.Flush();
 // 将当前所有缓冲的输出关闭
 Response.Close();
}

参考http://www.cnblogs.com/chengxiaohui/articles/1914217.html

你可能感兴趣的:(C#)