asp.net下载网络文件
时间:2011-02-19 来源:程序诗人
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;
}
具体的代码我都已经注释过了,希望有用。
相关阅读 更多 +