C# - 呼叫上傳檔案API名含中文時的處理 & 計算檔案hash值需注意Stream需先歸零

最近在開發上傳檔案API, 遇到呼叫端送來的檔案名稱變成亂碼,一查之下,發現原因是:

- the 'filename' parameter should be encoded on the wire. Non-ASCII characters should not be directly used; rather, they should be encoded in some manner

- Directly using Chinese characters (which are non-ASCII) doesn't map to the RFC definition.


解決方式: (取自: https://github.com/dotnet/runtime/issues/22996)

"no one" seems to be following the RFC's thou:-) 

Here is a hack: 

var hackedFileName = new string(Encoding.UTF8.GetBytes("新建文本文档.txt").Select(b => (char)b).ToArray()); 

streamContent2.Headers.Add("Content-Disposition", $"form-data; name=\"files\"; filename=\"{hackedFileName}\""); 

multipartContent.Add(streamContent2);


另外, 開發時也遇到要比對檔案hash值, 在用sha256算出hash值之前, 記得將stream先歸零(倒帶)好,再計算,才能得到準確的結果:

MemoryStream.Position = 0;

因我能直接取到Stream,所以直接用MemoryStream做, 其實道理在FileStream也是相同的:

FileStream.Position = 0;

(詳細說明見: https://stackoverflow.com/questions/1715362/why-do-these-two-files-hash-to-the-same-value-when-i-use-memorystream)


留言

熱門文章