首 页IT知识库翔宇问吧收藏本站
当前位置:翔宇亭IT乐园IT知识库WEBASP.NET

如何在ASP.NET中下载文件

减小字体 增大字体 作者:Andrew Fenster  来源:c-sharpcorner.com  发布时间:2011-02-23 19:22:55

本文介绍了一种在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/


本文源自:翔宇亭——IT乐园(http://www.biye5u.com),转载请保留此信息!

知识评论评论内容只代表网友观点,与本站立场无关!

   评论摘要(共 0 条,得分 0 分,平均 0 分) 查看完整评论

用户名: 查看更多评论

分 值:100分 90分 80分 70分 60分 40分 20分

内 容:

请注意用语文明且合法,不要发布带有攻击性、侮辱性的言论,谢谢合作!

验证码:

关于本站 | 网站帮助 | 广告合作 | 网站声明 | 友情连接 | 网站地图 | 用户守则 | 联系我们
本站部分内容来自互联网,如有侵权,请来信告之,谢谢!
Copyright © 2007-2019 biye5u.com. All Rights Reserved.
网站备案号:黑ICP备13005378号-3