文件下载中文文件名乱码问题!

wosizy 2011-06-30 11:26:15
如题
代码如下

private void DownloadFile(string filename)
{
//文件是否存在
if (!System.IO.File.Exists(filename))
{
Common.ShowMessage.Show(Page, "suess1", "文件不存在!");
return;
}
else
{
//打开要下载的文件
System.IO.FileStream r = new System.IO.FileStream(filename, System.IO.FileMode.Open);
//设置基本信息
Response.Buffer = false;
Response.AddHeader("Connection", "Keep-Alive");
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + System.IO.Path.GetFileName(filename));
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + Server.UrlEncode(filename) + "\"");
Response.AddHeader("Content-Length", r.Length.ToString());
while (true)
{
//开辟缓冲区空间
byte[] buffer = new byte[1024];
//读取文件的数据
int leng = r.Read(buffer, 0, 1024);
if (leng == 0)//到文件尾,结束
break;
if (leng == 1024)//读出的文件数据长度等于缓冲区长度,直接将缓冲区数据写入
Response.BinaryWrite(buffer);
else
{
//读出文件数据比缓冲区小,重新定义缓冲区大小,只用于读取文件的最后一个数据块
byte[] b = new byte[leng];
for (int i = 0; i < leng; i++)
b[i] = buffer[i];
Response.BinaryWrite(b);
}
}
r.Close();//关闭下载文件
Response.End();//结束文件下载
}
}

不知道是咋回事 网上也找了资料 都没能改变啊!
...全文
305 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
wosizy 2011-07-14
  • 打赏
  • 举报
回复
随便说下!
liuchaolin 的方法只能在IE 上使用 其他浏览器就不行!
wosizy 2011-07-14
  • 打赏
  • 举报
回复
忘记说了liuchaolin 的说法也能实现!
wosizy 2011-07-13
  • 打赏
  • 举报
回复
12楼的办法 网上弄的吧 我早已试过 根本不行
问题早已解决 最近出差在外一直没有时间结贴

现在来结个贴

为了正确地编码,我参考一位外国人士的代码,使用了并改进了16进制编码方法。

在输出文件地地方使用的代码:
string path = request.PhysicalPath;//获取客户端请求的文件的物理地址
if (File.Exists(path))
{
string fileName = System.IO.Path.GetFileName(path); // 获取文件的名字
if (Request.UserAgent.Contains("MSIE") || Request.UserAgent.Contains("msie"))
{
// 如果客户端使用 Microsoft Internet Explorer,则需要编码
fileName = ToHexString(fileName); // 如果使用 fileName =Server.UrlEncode(fileName); 则会出现上文中出现的情况
}
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.WriteFile(path);
Response.End();
}

应该置于上述代码同一文件或可访问的其他类的几个函数:


/// <summary>
/// 为字符串中的非英文字符编码
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string ToHexString(string s)
{
char[] chars = s.ToCharArray();
StringBuilder builder = new StringBuilder();
for (int index = 0; index < chars.Length; index++)
{
bool needToEncode = NeedToEncode(chars[index]);
if (needToEncode)
{
string encodedString = ToHexString(chars[index]);
builder.Append(encodedString);
}
else
{
builder.Append(chars[index]);
}
}

return builder.ToString();
}

/// <summary>
///指定 一个字符是否应该被编码
/// </summary>
/// <param name="chr"></param>
/// <returns></returns>
private static bool NeedToEncode(char chr)
{
string reservedChars = "$-_.+!*'(),@=&";

if (chr > 127)
return true;
if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0)
return false;

return true;
}

/// <summary>
/// 为非英文字符串编码
/// </summary>
/// <param name="chr"></param>
/// <returns></returns>
private static string ToHexString(char chr)
{
UTF8Encoding utf8 = new UTF8Encoding();
byte[] encodedBytes = utf8.GetBytes(chr.ToString());
StringBuilder builder = new StringBuilder();
for (int index = 0; index < encodedBytes.Length; index++)
{
builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16));
}
return builder.ToString();
}

此外,针对一些浏览器做了一些特殊的处理,已经体现在本文示例代码的注释中。此代码已经能非常完好地解决问题了,在 Internet Explorer 、Opera、Firefox 及 Chrome 中得到的体验一致,支持中文,支持空格的正常输出。
手术刀 2011-07-05
  • 打赏
  • 举报
回复
string fileName = "哈哈哈.xlsx";//客户端保存的文件名
string filePath = Server.MapPath("~/ecel/技术部项目周报.xlsx");//路径

FileInfo fileInfo = new FileInfo(filePath);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + Server.UrlEncode(fileName) + "\"");
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.WriteFile(fileInfo.FullName);
Response.Flush();
Response.End();
wosizy 2011-07-01
  • 打赏
  • 举报
回复
估计是头文件的问题 ! 我自己琢磨下!
md5e 2011-07-01
  • 打赏
  • 举报
回复
头文件必需要utf-8,所以要转编码
wosizy 2011-07-01
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 liuchaolin 的回复:]
Response.AddHeader("Content-Disposition", "attachment;filename=
头文件只需要一个
HttpUtility.UrlEncode("乱码.txt"), System.Text.Encoding.UTF8)
[/Quote]
程序里边是一个头文件的的 这里 我是拿下面那句测试 看能不能改变中文乱码的问题!
md5e 2011-07-01
  • 打赏
  • 举报
回复
Response.AddHeader("Content-Disposition", "attachment;filename=
头文件只需要一个
HttpUtility.UrlEncode("乱码.txt"), System.Text.Encoding.UTF8)
wosizy 2011-07-01
  • 打赏
  • 举报
回复
Response.Buffer = false;
Response.AddHeader("Connection", "Keep-Alive");
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + System.IO.Path.GetFileName(filename));
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + Server.UrlEncode(filename) + "\"");
Response.AddHeader("Content-Length", r.Length.ToString());
主要是上面这几行代码的设置! 无论怎么怎么写 都是中文乱码 英文就没事
而且文件也不再项目的路径下 所以不希望再看到Server.MapPath
dalmeeme 2011-07-01
  • 打赏
  • 举报
回复
加一个:需要进行url编码。
		FileInfo downloadFile = new FileInfo(Server.MapPath("~/C语言概念题解答选编.doc"));
long fileSize = downloadFile.Length;
Response.Clear();
Response.ContentType = "application/x-zip-compressed";
Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(downloadFile.Name));
//不指明Content-Length用Flush的话不会显示下载进度
Response.AddHeader("Content-Length", fileSize.ToString());
Response.TransmitFile(Server.MapPath("~/C语言概念题解答选编.doc"), 0, fileSize);
Response.Flush();
Response.Close();
md5e 2011-07-01
  • 打赏
  • 举报
回复
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", HttpUtility.UrlEncode("乱码.txt"), System.Text.Encoding.UTF8));
Response.AddHeader("Content-Length", len.ToString());
Response.ContentType = "application/octet-stream";
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.UTF8;
wosizy 2011-07-01
  • 打赏
  • 举报
回复
没人啊? 还是分少了! 这个问题 网上的资料我都看过了! 均未能解决
谁有做过这方面的经验?希望来探讨下 到底是啥原因
llovecf 2011-06-30
  • 打赏
  • 举报
回复
之前遇到过, 这个问题是页面的编码问题貌似,可以试下页面或者AddHeader里设置charset 与服务器输出的编码相同或者直接UTF-8 貌似我是这么解决的 希望对您有用
wosizy 2011-06-30
  • 打赏
  • 举报
回复
这么晚了 没人了 本来还想今天弄好这个的 看来只有明天自己去弄了

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧