Asp.net mvc FileContentResult和国际字符
我正在使用fileContentResult将文件渲染到浏览器。它工作得很好,只是当文件名包含国际字符时会引发异常。 我记得在某个地方读到,这个功能不支持国际字符,但我确信,如果应用程序需要在美国以外的国家上载文件,人们一定会遵循解决方法或最佳实践 有人知道这样的做法吗?这里是ActionResult方法Asp.net mvc FileContentResult和国际字符,asp.net-mvc,Asp.net Mvc,我正在使用fileContentResult将文件渲染到浏览器。它工作得很好,只是当文件名包含国际字符时会引发异常。 我记得在某个地方读到,这个功能不支持国际字符,但我确信,如果应用程序需要在美国以外的国家上载文件,人们一定会遵循解决方法或最佳实践 有人知道这样的做法吗?这里是ActionResult方法 public ActionResult GetFile(byte[] value, string fileName) { string fileExtension =
public ActionResult GetFile(byte[] value, string fileName)
{
string fileExtension = Path.GetExtension(fileName);
string contentType = GetContentType(fileExtension); //gets the content Type
return File(value, contentType, fileName);
}
提前谢谢
Susan我认为不可能下载文件名中带有国际字符的文件。文件名是
内容配置
头的一部分,与所有HTTP头一样,除了ASCII之外,没有其他方法可以在所有浏览器和代理中使用
不过,上传带有国际字符的文件应该没有问题,因为文件名是以普通格式数据传输的(
应用程序/www-url-encoded
)我认为这取决于您的响应标题编码(请参阅)
嗯,
埃里克
从UTF-8或Win1250获取的字节大小不同。您必须以正确的编码方式从字符串中获取字节,从而正确地解释字符串。我知道,但我在一些网站上尝试过这种方法,而且它对瑞典字符很有效,因此必须有另一种解决方案。例如,如果你将一个文件附加到gmail并下载它,即使它有国际字符,它仍然可以正常工作。我能想到的一件事是将文件直接附加到响应中,但我如何在MVC中将其发送回客户机?您可以尝试反向工程Google如何执行此操作,并创建自己的从ActionResult派生的类,在该类中,您可以返回任何您想要的内容(受ASP.NET允许您执行的操作的限制).当FileDownloadName中也有国际字符时,它能工作吗?@rezarahmati不幸的是不能。但对于国际文件名,您可以使用以下示例:
public class UnicodeFileContentResult : ActionResult {
public UnicodeFileContentResult(byte[] fileContents, string contentType) {
if (fileContents == null || string.IsNullOrEmpty(contentType)) {
throw new ArgumentNullException();
}
FileContents = fileContents;
ContentType = contentType;
}
public override void ExecuteResult(ControllerContext context) {
var encoding = UnicodeEncoding.UTF8;
var request = context.HttpContext.Request;
var response = context.HttpContext.Response;
response.Clear();
response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", (request.Browser.Browser == "IE") ? HttpUtility.UrlEncode(FileDownloadName, encoding) : FileDownloadName));
response.ContentType = ContentType;
response.Charset = encoding.WebName;
response.HeaderEncoding = encoding;
response.ContentEncoding = encoding;
response.BinaryWrite(FileContents);
response.End();
}
public byte[] FileContents { get; private set; }
public string ContentType { get; private set; }
public string FileDownloadName { get; set; }
}
public FileContentResult XmlInvoice(Order order)
{
string stream = order.Win1250StringData;
var bytes = Encoding.GetEncoding("windows-1250").GetBytes(stream);
var fr = new FileContentResult(bytes, "application/xml");
fr.FileDownloadName = string.Format("FV{0}.xml", order.DocumentNumber);
return fr;
}