asp.net下载网络文件

在网站设计过程中,我们常常需要下载一些上传的文件,比如说压缩包,文档,影视资源等等。那么我们就需要一个能够提供下载的功能,当然了 一般的下载功能应该能够提示用户保存或者是打开,在下载过程中能够实时的提示进度和速度,并且提示下载的大小。在下载过程中,能够在出错的时候,进行异常报错。这将是再好不过的了,今天的例子,就调用了系统的下载例子,具体见代码:

private bool DownLoadFile()
{
//文件路径 和 文件名称
string filePath = Server.MapPath("~/DownLoad/myFiles");
string downLoadFile = "test.mkv";

FileInfo fileName
= new FileInfo(filePath + "\\" + downLoadFile);
FileStream fileStream
= new FileStream(filePath + "\\" + downLoadFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

//流读取
BinaryReader binaryReader = new BinaryReader(fileStream);

//如果文件存在
if (fileName.Exists)
{
try
{
long startBytes = 0;
string lastUpdateTimeStamp = File.GetLastWriteTimeUtc(filePath).ToString("r");
string encodeData = HttpUtility.UrlEncode(downLoadFile, Encoding.UTF8) + lastUpdateTimeStamp;

//清除response的内容
Response.Clear();
Response.Buffer
= false;
Response.AddHeader(
"Accept-Ranges", "bytes");
Response.AppendHeader(
"ETag", "\"" + encodeData + "\"");
Response.AppendHeader(
"Last-Modified", lastUpdateTimeStamp);

//设置contenttype
Response.ContentType = "application/octet-stream";

//在弹出的对话框中,添加上文件名称和文件大小
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName.Name);

Response.AddHeader(
"Content-Length", (fileName.Length - startBytes).ToString());
Response.AddHeader(
"Connection", "Keep-Alive");

//设置编码格式
Response.ContentEncoding = Encoding.UTF8;

//发送数据
binaryReader.BaseStream.Seek(startBytes, SeekOrigin.Begin);

//切割数据,以1024字节为一个包
int maxCount = (int)Math.Ceiling((fileName.Length - startBytes + 0.0) / 1024);

//以1024为单位,下载数据
int i;
for (i = 0; i < maxCount && Response.IsClientConnected; i++)
{
Response.BinaryWrite(binaryReader.ReadBytes(
1024));
Response.Flush();
}

//将当前的下载与总文件大小对比,看看是否下载完毕
if (i < maxCount) return false;
return true;
}
catch
{
return false;
}
finally
{
//文件流以及流读取关闭
Response.End();
binaryReader.Close();
fileStream.Close();
}
}
else
{
ScriptManager.RegisterStartupScript(
this, GetType(), "文件不存在", "alert('文件不存在!')", true);
}
return false;
}

具体的代码我都已经注释过了,希望有用。

原文地址:https://www.cnblogs.com/scy251147/p/1958610.html