1

私は、任意の言語でエクスポートできる必要があるデータエクスポートタスクに取り組んでいます。厳密にASCII文字を使用するすべての言語は問題なく動作しますが、東洋の言語でデータをエクスポートすると、次の例外がスローされます。「メールヘッダーに無効な文字が見つかりました」少し調べて、これを判断しました。これは、「78文字より長い、または非ASCII文字を含むパラメーター値は[RFC2184]で指定されているようにエンコードする必要がある」と述べているRFC2183仕様によるものです。

私はこれらのドキュメントの両方を読みましたが、あまり役に立ちませんでした。ファイルを見つけるには、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以外の文字を保持できるようにする方法を探しています。

どんな助けでも大歓迎です。

4

1 に答える 1

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

You'll need to catch any other characters it considers special as well as % here. If those special characters are the same as those special to URIs, you could just use Uri.EscapeDataString(s).

于 2011-12-19T22:17:56.407 に答える