public void DownloadFile(string fileId) { //Stream fileStream = null; try { int fileID = Convert.ToInt32(fileId); string RelatePath = fileInfoBLL.GetRelatePath(fileID); string fileFullPath = filePath + "\\" + RelatePath; string fileName = fileInfoBLL.GetFileName(fileID); var response = HttpContext.Current.Response; response.Clear(); response.Buffer = true; //fileName = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.GetEncoding("UTF-8")); response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); response.ContentEncoding = System.Text.Encoding.UTF8; response.Charset = "UTF-8"; response.WriteFile(fileFullPath); } catch (Exception ex) { ExceptionHandler.ExceptionHelper.Instance.HandleException(ex); } }
将字符串转换成指定编码格式:
1 string fileName = System.Web.HttpUtility.UrlEncode("要转换的字符串", System.Text.Encoding.GetEncoding("UTF-8")); 2 string gbStr = System.Text.Encoding.GetEncoding("gb2312").GetString(System.Text.Encoding.Default.GetBytes(‘xxx‘));
另一种:
1 private void DownloadFile(string fileName, string filePath) 2 { 3 try 4 { 5 if (!string.IsNullOrEmpty(filePath)) 6 { 7 if (string.IsNullOrEmpty(fileName)) 8 { 9 fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1); 10 } 11 12 context.Response.Clear(); 13 context.Response.Buffer = true; 14 context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlPathEncode(fileName)); 15 context.Response.ContentEncoding = System.Text.Encoding.UTF8; 16 context.Response.Charset = "UTF-8"; 17 //context.Response.ContentType = "application/vnd.ms-excel"; 18 context.Response.WriteFile(UploadFileSavePath + "\\" + filePath); 19 } 20 } 21 catch (Exception ex) 22 { 23 ExceptionHelper.Instance.HandleException(ex); 24 context.Response.Write("{\"bizSuccess\":false,\"msg\":\"下载文件时发生错误!\"}"); 25 } 26 27 context.Response.Flush(); 28 context.Response.End(); 29 }
原文:http://www.cnblogs.com/lihongchen/p/3699153.html