mvc附件下载,以及中文名称乱码问题

    xiaoxiao2021-03-25  91

    /// <summary>         /// 下载附件         /// </summary>         /// <param name="fileID"></param>         /// <returns></returns>         public ActionResult Show()         {             Response.HeaderEncoding = Encoding.UTF8;             TAttachmentBusiness filebll = new TAttachmentBusiness();             string fileid = Request.QueryString["fileID"];             var attachment = filebll.GetTAttachmentByID(fileid);             string fileName = attachment.FileName;             string filePath = attachment.FilePath;             WebCommon.SetNetPostion();             FileStream fs = new FileStream(filePath, FileMode.Open);             byte[] bytes = new byte[(int)fs.Length];             fs.Read(bytes, 0, bytes.Length);                         fs.Close();             if (Request.UserAgent != null)             {                 string userAgent = Request.UserAgent.ToUpper();                 if (userAgent.IndexOf("FIREFOX", StringComparison.Ordinal) <= 0)                     fileName = ToUtf8String(fileName);             }             Response.Charset = "UTF-8";            // Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");             Response.ContentType = "application/octet-stream";             Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);             Response.BinaryWrite(bytes);             Response.Flush();             WebCommon.CancelNetPostion();             Response.End();             return new EmptyResult();         }         /// <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();         }
    转载请注明原文地址: https://ju.6miu.com/read-19408.html

    最新回复(0)