您的位置:首页 > 编程语言 > C#

c# execl下载 兼容火狐 ie 谷歌

2017-02-10 10:12 411 查看
protected void LoadTemplet_Click(object sender, EventArgs e)
{
string fileName = "节假日导入模板.xls";//客户端保存的文件名

//filePath 为文件路径
string filePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["HolidayTemplet"].ToString());//路径
string savePath = filePath;

if (System.IO.File.Exists(savePath))
{
long chunkSize = 204800;             //指定块大小
byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区
long dataToRead = 0;                 //已读的字节数
FileStream stream = null;
try
{
Encoding encoding;
string outputFileName = null;
string browser = HttpContext.Current.Request.UserAgent.ToUpper();
if (browser.Contains("MS") == true && browser.Contains("IE") == true)
{
outputFileName = HttpUtility.UrlEncode(fileName);
encoding = System.Text.Encoding.Default;
}
else if (browser.Contains("FIREFOX") == true)
{
outputFileName = fileName;
encoding = System.Text.Encoding.GetEncoding("GB2312");
}
else
{
outputFileName = HttpUtility.UrlEncode(fileName);
encoding = System.Text.Encoding.Default;
}
//打开文件
stream = new FileStream(savePath, FileMode.Open, FileAccess.Read, FileShare.Read);
dataToRead = stream.Length;

//添加Http头
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentEncoding = encoding;
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + outputFileName);
HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString());

while (dataToRead > 0)
{
if (HttpContext.Current.Response.IsClientConnected)
{
int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Clear();
dataToRead -= length;
}
else
{
dataToRead = -1; //防止client失去连接
}
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("Error:" + ex.Message);
}
finally
{
if (stream != null) stream.Close();
HttpContext.Current.Response.Close();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐