2011-09-13 4 views
1

모든 언어로 내보낼 수 있어야하는 데이터 내보내기 작업을하고 있습니다. 엄격하게 ASCII 문자를 사용하는 모든 언어는 정상적으로 작동하지만 동양 언어로 데이터를 내보낼 때 다음과 같은 예외가 발생합니다. "잘못된 문자가 메일 헤더에서 발견되었습니다."약간의 연구를 통해 "78 문자보다 긴 매개 변수 값 또는 비 ASCII 문자가 포함 된 매개 변수 값은 [RFC 2184]에 지정된대로 인코딩해야합니다".Net MVC 2, 파일 이름에 비 ASCII 문자가 포함 된 파일 반환

이러한 두 가지 문서를 모두 읽었을 때, 도움이되지 않습니다. 파일을 찾으려면 UTF-8 인코딩으로 데이터를 보낼 필요가 있음을 이해합니다. 그러나 이렇게하면 다운로드 한 파일 이름이 인코딩 된 UTF-8로 나타납니다. 현재 필자는 아래에 게시 할 함수를 사용하여 파일 이름을 UTF로 인코딩합니다. (이 모든 MVC2, C#에서이다)

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-Encoded로 끝납니다. 그 비 ASCII 문자를 유지할 수 있도록 기존 파일을 사용자에게 다시 전달하는 방법을 찾고 있습니다.

도움을 주시면 감사하겠습니다.

답변

0

이것은 UTF-8 인코딩이 아닌 utf-8 기반 URI 인코딩의 변형입니다. 우리는 다음과 같이 고칠 수 있습니다 :

private static string GetCleanedFileName(string s) 
{ 
    StringBuilder sb = new StringBuilder(); 
    foreach(byte b in Encoding.UTF8.GetBytes(s)) 
    { 
    if(b < 128 && b != 0x25)// ascii and not % 
     sb.Append((char)b); 
    else 
     sb.Append('%').Append(b.ToString("X2")); 
    } 
    return sb.ToString(); 
} 

여기에 %뿐만 아니라 특별하다고 간주되는 다른 문자도 잡아야합니다. 이 특수 문자가 URI 특수 문자와 동일한 경우 Uri.EscapeDataString(s) 만 사용할 수 있습니다.