ASP.NET直接下载文件

一. 服务端通过Response输出相应的HTTP Response Headers信息,和要下载的文件的数据来把文件发送到客户端,HTTP Response Headers表现在html文件中是下面的形式:
<meta http-equiv="Content-Type" content="text/htm ">
http-equiv表示是Headers的名称,content表示这个Headers的值

二. 首先,要输出文件的MIME类型:
Page.Response.AddHeader( "Content-Type", “MIME类型” );

三. 其次,要输出下载的文件的打开位置和文件名:
Page.Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName );
content-disposition 的 HTTP response header 允许指定文档表示的信息。使用这种 header ,你就可以将文档指定成单独打开(而不是在浏览器中打开),还可以根据用户的操作来显示。如果用户要保存文档,你还可以为该文档建议一个文件名。这个建议名称会出现在 Save As 对话框的“文件名”栏中。
attachment ―― 表示作为附件发送到客户端,客户端将单独打开此文件。
inline ―― 表示将在浏览器中打开这个文件。
filename ―― 表示发送到客户端文件的文件名。

四. 准备发送到客户端的文件数据:
不管什么类型的文件都要先转成byte类型的数组,然后将这个byte数组用Response.BinaryWrite方法输出到客户端。

   string path ="G://download//down.txt";
   System.IO.FileInfo file = new System.IO.FileInfo(path);
   Response.Clear();
   Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file.Name));

   Response.AddHeader("Content-Length", file.Length.ToString());
   Response.ContentType = "application/octet-stream";
   Response.WriteFile(file.FullName);
   Response.End();


string FileName =
 ((LinkButton)sender).CommandArgument;
          Response.Clear();
          Response.ContentType 
= "application/octet-stream"
;
          Response.AddHeader(
"Content-Disposition""attachment;FileName=" +
 HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));
          Response.WriteFile(
this.Folder+@"/"+
FileName);
          Response.End();


private string checktype(string filename)
{
string ContentType;
switch( filename.Substring(filename.LastIndexOf(".")).Trim().ToLower())
{
case ".asf":
ContentType = "video/x-ms-asf";
break;
case ".avi":
ContentType = "video/avi";
break;
case ".doc":
ContentType = "application/msword";break;
case ".zip":
ContentType = "application/zip"; break;
case ".xls":
ContentType = "application/vnd.ms-excel";break;
case ".gif":
ContentType = "image/gif"; break;
case ".jpg":
ContentType = "image/jpeg";break;
case  "jpeg":
ContentType = "image/jpeg";break;
case ".wav":
ContentType = "audio/wav";break;
case ".mp3":
ContentType = "audio/mpeg3";break;
case ".mpg":
ContentType = "video/mpeg";break;
case ".mepg":
ContentType = "video/mpeg";break;
case ".rtf":
ContentType = "application/rtf";break;
case ".html":
ContentType = "text/html";break;
case ".htm":
ContentType = "text/html";break;
case ".txt":
ContentType = "text/plain";break;
default :
ContentType = "application/octet-stream";
break;
}
return ContentType;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值