- ·上一篇文章:在asp.net中计算两个日期相差的年、月、小时、分钟 、秒等
- ·下一篇文章:在ASP.NET中管理各种状态
如何在ASP.NET中下载文件
本文介绍了一种在ASP.NET中下载文件的方法。
这里给出的在ASP.NET应用程序中下载文件的方法,可能是最简单的、最短的方式:
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=MyFile.pdf");
Response.TransmitFile(Server.MapPath("~/Files/MyFile.pdf"));
Response.End();
第一步是设置文档内容类型,在上面的例子里,我们准备下载一个.pdf文件。下面是最常用的一些文档内容类型:
.htm, .html Response.ContentType = "text/HTML";
.txt Response.ContentType = "text/plain";
.doc, .rtf, .docx Response.ContentType = "Application/msword";
.xls, .xlsx Response.ContentType = "Application/x-msexcel";
.jpg, .jpeg Response.ContentType = "image/jpeg";
.gif Response.ContentType = "image/GIF";
.pdf Response.ContentType = "application/pdf";
Response.TransmitFile方法检索一个文件并将其写到Response区。通过调用TransmitFile,你将在浏览器中打开“打开/保存”对话框,而不仅仅是在浏览器窗口中打开文件。
在一些情况下,由于我们不能确定文件按的路径,而不能调用TransmitFile方法。取而代之的是是将文件看做“流(Stream)”将其写入Response对象。
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=MyFile.pdf");
// Write the file to the Response
const int bufferLength = 10000;
byte[] buffer = new Byte[bufferLength];
int length = 0;
Stream download = null;
try
{
download = new FileStream(Server.MapPath("~/Files/Lincoln.txt"),
FileMode.Open, FileAccess.Read);
do
{
if (Response.IsClientConnected)
{
length = download.Read(buffer, 0, bufferLength);
Response.OutputStream.Write(buffer, 0, length);
buffer = new Byte[bufferLength];
}
else
{
length = -1;
}
}
while (length > 0);
Response.Flush();
Response.End();
}
finally
{
if (download != null)
download.Close();
}
通过以上的代码,我们可以在浏览器中打开一个“打开/保存”对话框来下载并保存文件。
下面的代码在包含上面所述代码及实现技术:
本文转载于c-sharpcorner.com,由本站(翔宇亭IT乐园)翻译,要转载时,请保留此信息,原文地址:http://www.c-sharpcorner.com/UploadFile/afenster/5725/
!
如何在ASP.NET中下载文件