今天在遷移一個老系統到新服務器的時候,在測試下載接口的時候發現:同一個接口,有些文件可以下載,有些文件不能下載。
調試了半天發現,好像是文件名的問題。
string fileName = "38374-fjf(1).13jk";
string contentDisposition = string.Format("attachment;filename={0}",fileName);
msg.Content.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse(contentDisposition);

於是乎悲劇了。
然后我百度了一下,網上似乎都是什么書說文件名亂碼的,沒有一個說說是我這種清空情況。
無奈去查了一下標准文檔 http://www.ietf.org/rfc/rfc6266.txt
跳過前面的定義直接看例子
5. Examples
Direct the UA to show "save as" dialog, with a filename of
"example.html":
Content-Disposition: Attachment; filename=example.html
Direct the UA to behave as if the Content-Disposition header field
wasn't present, but to remember the filename "an example.html" for a
subsequent save operation:
Content-Disposition: INLINE; FILENAME= "an example.html"
Note: This uses the quoted-string form so that the space character
can be included.
Direct the UA to show "save as" dialog, with a filename containing
the Unicode character U+20AC (EURO SIGN):
Content-Disposition: attachment;
filename*= UTF-8''%e2%82%ac%20rates
Here, the encoding defined in [RFC5987] is also used to encode the
non-ISO-8859-1 character.
This example is the same as the one above, but adding the "filename"
parameter for compatibility with user agents not implementing
RFC 5987:
Content-Disposition: attachment;
filename="EURO rates";
filename*=utf-8''%e2%82%ac%20rates
Note: Those user agents that do not support the RFC 5987 encoding
ignore "filename*" when it occurs after "filename".
Note: This uses the quoted-string form so that the space character
can be included.
看到這句我似乎發現了什么。如果有空格就需要寫成字符串引用的格式。
string contentDisposition = string.Format("attachment;filename=\"{0}\"", fileName);
文件名有特殊符號是解決了,比如括號,空格什么的。但是如果文件名當中有中午,下載時候的默認文件名缺還是亂碼。
這個網上有一堆解決方案。
string fileName= HttpUtility.UrlEncode("啊fnam(4)e.ext",UTF8Encoding.UTF8);
其實只要對文件名做一次Encode轉碼就行了。

就這個簡單的問題,耗費了我一個小時。
今天就先到這里,晚安。
