.net MVC 下载文件乱码问题解决方案
- public ActionResult OverAllSummaryExport(string id)
- {
- #region 解决中文乱码
- Response.HeaderEncoding = Encoding.UTF8;
- string fileName = "安全生产标准化自评结果整体输出.doc";
- if (Request.UserAgent != null)
- {
- string userAgent = Request.UserAgent.ToUpper();
- if (userAgent.IndexOf("FIREFOX", StringComparison.Ordinal) <= 0)
- fileName = ToUtf8String(fileName);
- }
- #endregion
- string HTMLStr =string.Format("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">{0}</head><body>{1}</body></html>",GetStyle(),GetBody(id));
- return File(Encoding.UTF8.GetBytes(HTMLStr), "application/vnd.ms-word", fileName);
- }
- /// <summary>
- /// 解决下载名称在IE下中文乱码
- /// </summary>
- /// <param name="s"></param>
- /// <returns></returns>
- private String ToUtf8String(String s)
- {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < s.Length; i++)
- {
- char c = s[i];
- if (c >= 0 && c <= 255)
- {
- sb.Append(c);
- }
- else
- {
- byte[] b;
- try
- {
- b = Encoding.UTF8.GetBytes(c.ToString());
- }
- catch (Exception ex)
- {
- b = new byte[0];
- }
- for (int j = 0; j < b.Length; j++)
- {
- int k = b[j];
- if (k < 0) k += 256;
- sb.Append("%" + Convert.ToString(k, 16).ToUpper());
- }
- }
- }
- return sb.ToString();
- }