45fan.com - 路饭网

搜索: 您的位置主页 > 网络频道 > 阅读资讯:怎么样能实现在asp.net中下载文件功能?

怎么样能实现在asp.net中下载文件功能?

2016-08-29 15:40:15 来源:www.45fan.com 【

怎么样能实现在asp.net中下载文件功能?

例一:
1.C#.net
/// <summary>
/// 文件下载
/// </summary>
/// <param name="FullFileName"></param>
private void FileDownload(string FullFileName)
{
FileInfo DownloadFile = new FileInfo(FullFileName);
Response.Clear();
Response.ClearHeaders();
Response.Buffer=false;
Response.ContentType="application/octet-stream";
Response.AppendHeader("Content-Disposition","attachment;filename=" +HttpUtility.UrlEncode(DownloadFile.FullName,System.Text.Encoding.UTF8));
Response.AppendHeader("Content-Length",DownloadFile.Length.ToString());
Response.WriteFile(DownloadFile.FullName);
Response.Flush();
Response.End();
}
设置保存文件格式(example: *.xls):
Response.ContentType = "application/ms-excel";

例二:
System.IO.FileStream r = new System.IO.FileStream(Server.MapPath("."+"/overlibw.js"), System.IO.FileMode.Open);
//设置基本信息
Response.Buffer = false;
Response.AddHeader("Connection", "Keep-Alive");
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + System.IO.Path.GetFileName(FileName));
Response.AddHeader("Content-Length", r.Length.ToString());
while (true)
{
//开辟缓冲区空间
byte[] buffer = new byte[1024];
//读取文件的数据
int leng = r.Read(buffer, 0, 1024);
if (leng == 0)//到文件尾,结束
break;
if (leng == 1024)//读出的文件数据长度等于缓冲区长度,直接将缓冲区数据写入
Response.BinaryWrite(buffer);
else
{
//读出文件数据比缓冲区小,重新定义缓冲区大小,只用于读取文件的最后一个数据块
byte[] b = new byte[leng];
for (int i = 0; i < leng; i++)
b[i] = buffer[i];
Response.BinaryWrite(b);
}
}
r.Close();//关闭下载文件
Response.End();//结束文件下载

 

本文地址:http://www.45fan.com/a/question/69430.html
Tags: 实现 文件 ASP.NET
编辑:路饭网
关于我们 | 联系我们 | 友情链接 | 网站地图 | Sitemap | App | 返回顶部