首页 > 开发 > .Net > 正文

如何在ASP.NET中下载文件

2023-04-26 12:25:50
字体:
来源:转载
供稿:网友

本文介绍了一种在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();
        }

通过以上的代码,我们可以在浏览器中打开一个“打开/保存”对话框来下载并保存文件。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表