ASP.NET 输出文件(下载文件)几种示例
本文发布于 8 年前,部分内容可能已经失去参考价值。
将字符串作为文本文档输出:
Response.AddHeader("Content-Disposition", "attachment; filename=文件名.txt"); Response.Write(字符串内容); Response.End();
直接提供服务器文件下载:
FileInfo thefile = new FileInfo(path); Response.Clear(); Response.ClearHeaders(); Response.Buffer = false; Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("刮刮卡参与") + id + ".csv"); Response.AppendHeader("Content-Length", thefile.Length.ToString()); Response.WriteFile(thefile.FullName); Response.Flush(); Response.End();
输出使用 NPOI 创建的 Excel(MemoryStream):
HSSFWorkbook book = new HSSFWorkbook(); …… MemoryStream ms = new MemoryStream(); book.Write(ms); Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", scene.d.drama + " " + scene.s.time_show.ToString("yyyy年MM月dd日HH时mm分"))); Response.BinaryWrite(ms.ToArray()); Response.End(); book = null; ms.Close(); ms.Dispose();
最后,如果要指定文件编码,加上这句就行:
Response.ContentEncoding = Encoding.xxx;
可能相关的内容