2009-07-16 56 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獲取的字節大小不同。您必須通過從正確編碼中的字符串獲取字節來解釋字符串的正確方式。