asp.net文件下载中文文件名乱码解决

private static void ExportSave(IWorkbook workbook, ISheet sheet, string filename)
        {
            MemoryStream ms = new MemoryStream();

            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;
            sheet = null;
            workbook = null;
            //sheet.Dispose();
            //workbook.Dispose();


            byte[] data = ms.ToArray();
            //fs.Write(data, 0, data.Length);           
            HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            //Encoding pageEncode = Encoding.GetEncoding(PageEncode);
            response.Charset = "UTF-8";
            response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel";

            response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + filename));
            response.BinaryWrite(data);
            response.Flush();
            response.End();
        }


文件下载时要用到MemoryStream这个类,用它将你的文件转化为输出流,再用HttpResponse的BinaryWrite方法将流字节输出,如上。

但传入的文件名总是会乱码。这是因为我们的浏览器默认的字符格式为UTF-8,而在程序中的中文字符默认为GBK(gb2312)格式,解决办法是将中文字段输入默认的网页格式。如使用Server.UrlEncode(fileName)可以解决

你可能感兴趣的:(asp.net文件下载中文文件名乱码解决)