none
Problem uploading file with non-ASCII file name using HttpClient RRS feed

  • Question

  • We are using the MultipartFormDataContent object with a StreamContent item to upload a file using HttpClient:

       FileStream filestream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
       StreamContent streamContent = new StreamContent(filestream);
       content.Add(streamContent, "\"FileField\"", "\"" + System.IO.Path.GetFileName(filePath) + "\"");
       HttpRequestMessage message = CreateMessage(HttpMethod.Post, new Uri(url), content);
       HttpClient client = CreateClient();
       client.SendAsync(message, HttpCompletionOption.ResponseContentRead);

    The problem we are encountering is that when we upload a document with Chinese characters the file name is base64 encoded like this: =?utf-8?B?w6DDosOmw6fDqcOow6rDq8Ovw67DtMWTw7nDu8O8w7/kuIvpmaLnt48uZG9jeA==?=. Unfortunately, on the server side, HttpPostedFile does not decode the name.

    This encoding may be correct by RFC2047, but I cannot find a way to either control whether this encoding occurs, or an API that will decode it properly on the server. Any suggestions?

    Thanks,

    Jeff Montgomery

    Wednesday, June 11, 2014 8:43 PM

Answers

  • Maybe you can always encode the filename using this expression: Convert.ToBase64String( Encoding.UTF8.GetBytes( filename ) ). Then use the string in content.Add. Such string will not be re-encoded by the system. On the receiver side, use this expression to get back the real name: Encoding.UTF8.GetString( Convert.FromBase64String( postedFile.FileName ) ).


    Thursday, June 12, 2014 6:16 AM

All replies

  • Most stream classes default to ASCII encoding which won't work with Unicode files.  Try code below

                FileStream filestream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader reader = new StreamReader(filestream, Encoding.Unicode);


    jdweng

    Thursday, June 12, 2014 12:52 AM
  • Maybe you can always encode the filename using this expression: Convert.ToBase64String( Encoding.UTF8.GetBytes( filename ) ). Then use the string in content.Add. Such string will not be re-encoded by the system. On the receiver side, use this expression to get back the real name: Encoding.UTF8.GetString( Convert.FromBase64String( postedFile.FileName ) ).


    Thursday, June 12, 2014 6:16 AM