2009-07-16 81 views
5

我正在使用fileContentResult将文件呈现给浏览器。它运行良好,除了当fileName包含国际字符时引发异常。 我记得在某个地方看到这个功能不支持国际字符,但我相信在应用程序需要在美国以外的国家上传文件时,必须有一种解决方法或人们遵循的最佳做法。FileContentResult和国际字符

有谁知道这种做法的呢?下面是ActionResult的方法提前

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); 
    } 

感谢

苏珊

回答

6
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; } 
} 
0

我不认为这是可以下载与国际字符的文件文件名。文件名是Content-disposition标题的一部分,并且与所有HTTP标题一样,除了ASCII以外,不能使用除所有浏览器和代理之外的其他编码。

与国际字符上传的文件应该是没有问题的,不过,因为文件名作为普通表单数据(application/www-url-encoded

+0

我知道,但我在几个网站上试过,并且它与瑞典字符很好地协作,所以必须有一个备用解决方案。例如,如果您将文件附加到Gmail并下载它,即使它具有国际字符,它仍然可以正常工作。我能想到的一件事是将文件直接附加到响应中,但是如何将它发送回MVC中的客户端? – suzi167 2009-07-16 19:58:50

+0

您可以尝试反向设计Google如何执行此操作,并创建自己的从ActionResult派生的类,您可以在其中返回任何您想要的内容(受限于ASP.NET允许您执行的操作)。 – chris166 2009-07-17 05:18:15

0
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; 
} 

从UTF-8或Win1250获取的字节大小不同。您必须通过从正确编码中的字符串获取字节来解释字符串的正确方式。