【发布时间】:2011-09-13 14:00:11
【问题描述】:
我正在处理需要能够以任何语言导出的数据导出任务。所有严格使用 ASCII 字符的语言都可以正常工作,但是当我使用东方语言进行数据导出时,它会抛出以下异常:“在邮件标题中发现了一个无效字符” 经过一番研究,我确定这是由于 RFC 2183 规范规定“参数值超过 78 个字符,或包含非 ASCII 字符,必须按照 [RFC 2184] 中的规定进行编码”
我阅读了这两个文件,但它们并没有太大帮助。我了解需要以 UTF-8 编码发送数据才能找到文件。但是,这会使下载的文件名显示为编码的 UTF-8。到目前为止,我正在使用我将在下面发布的函数将文件名编码为 UTF。 (所有这些都在 C#、MVC2 中)
private static string GetCleanedFileName(string s)
{
char[] chars = s.ToCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars.Length; i++)
{
string encodedString = EncodeChar(chars[i]);
sb.Append(encodedString);
}
return sb.ToString();
}
private static string EncodeChar(char chr)
{
UTF8Encoding encoding = new UTF8Encoding();
StringBuilder sb = new StringBuilder();
byte[] bytes = encoding.GetBytes(chr.ToString());
for (int index = 0; index < bytes.Length; index++)
{
sb.AppendFormat("%{0}", Convert.ToString(bytes[index], 16));
}
return sb.ToString();
}
并且文件在以下函数中返回:
[ActionName("FileLoad")]
public ActionResult FileLoad()
{
string fileName = Request["fileName"];
//Code that contains the path and file type Removed as it doesn't really apply to the question
FileStream fs = new FileStream(filePath, FileMode.Open);
return File(fs, exportName, GetCleanedFileName(fileName));
}
严格来说,这是可行的。但是,整个文件名在到达用户时会以 UTF 编码结束。我正在寻找一种将预先存在的文件传回给用户的方法,以便它可以保留其非 ASCII 字符。
感谢任何帮助。
【问题讨论】:
标签: c# asp.net-mvc-2 download non-ascii-characters