ASP.NET文件下载详细步骤
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using YTLib.Basic;
using YTLib.YTDBC;
using System.IO;
using System.Threading;
namespace siteadmin.admin
{
public partial class downfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strSQL = "";
YTNDBObject dbo = new YTNDBObject();
dbo.DataName = "Main";
Page.EnableViewState = false;
if(!IsPostBack)
{
string sid=Request["id"];
if(!YTLib.publicOP.IsNumString(sid)||sid==null)
sid="0";
strSQL = "select * from FileSource where ID=@ID";
dbo.PrepareCommand(strSQL);
dbo.SetCmdIntValue("@ID",int.Parse(sid));
DataTable dt=dbo.QueryData().Tables[0];
string sourceName = (string)dt.Rows[0]["FilePath"];
sourceName.Trim();//消除空格
string filesnames = sourceName.Substring(7, sourceName.Length - 8);
int index= sourceName.LastIndexOf(".");
string extend = sourceName.Substring(index+1);//扩展名
string fullPath = "~/uploaded/" + sourceName;
fullPath = Server.MapPath(fullPath);
//读出该资源的下载次数
int downloadtimes = 0;
downloadtimes = int.Parse(dt.Rows[0]["downloadCounts"].ToString());
Page.Response.Clear();
bool success = ResponseFile(Page.Request, Page.Response, filesnames, fullPath, 1024000);
if (!success) Response.Write("<script language=\"javascript\">alert(\"Download file error\");window.location.href=\"../Download.aspx\"</script>");
else
{
//记录下载次数
downloadtimes++;
string sqlStr = "update FileSource set downloadCounts=" + downloadtimes + " where ID=@IID";
dbo.PrepareCommand(sqlStr);
dbo.SetCmdIntValue("@IID",int.Parse(sid));
dbo.ExecuteNoQuery();
}
Response.Write("<script language=\"javascript\">window.location.href=\"../Download.aspx\"</script>");
}
}
public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
{
try
{
FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
_Response.AddHeader("Accept-Ranges", "bytes");
_Response.Buffer = false;//不缓冲
long fileLength = myFile.Length;
long startBytes = 0;
double pack = 10240;
//10K bytes
int sleep = 200;
//每秒5次 即5*10K bytes每秒 int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = 206;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
//Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));
}
_Response.AddHeader("Connection", "Keep-Alive");
_Response.ContentType = "application/octet-stream";
_Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1;
for (int i = 0; i < maxCount; i++)
{
if (_Response.IsClientConnected)
{
_Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));
Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
return false;
}
return true;
}
}
}