asp.net文件的方法
asp.net文件的方法
ASP 是一項(xiàng)微軟公司的技術(shù),是一種使嵌入網(wǎng)頁中的腳本,可由因特網(wǎng)服務(wù)器執(zhí)行的服務(wù)器端腳本技術(shù)。下面是學(xué)習(xí)啦小編為大家?guī)砹艘黄猘sp.net下載文件的方法,希望對(duì)大家有所幫助。
asp.net下載文件的方法(一)
public class FileDown
{
public FileDown()
{ }
/// <summary>
/// 參數(shù)為虛擬路徑
/// </summary>
public static string FileNameExtension(string FileName)
{
return Path.GetExtension(MapPathFile(FileName));
}
/// <summary>
/// asp.net下載文件的方法:獲取物理地址
/// </summary>
public static string MapPathFile(string FileName)
{
return HttpContext.Current.Server.MapPath(FileName);
}
/// <summary>
/// 普通下載
/// </summary>
/// <param name="FileName">文件虛擬路徑</param>
public static void DownLoadold(string FileName)
{
string destFileName = MapPathFile(FileName);
if (File.Exists(destFileName))
{
FileInfo fi = new FileInfo(destFileName);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = false;
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Path.GetFileName(destFileName), System.Text.Encoding.UTF8));
HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.WriteFile(destFileName);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
/// <summary>
/// asp.net分塊下載
/// </summary>
/// <param name="FileName">文件虛擬路徑</param>
public static void DownLoad(string FileName)
{
string filePath = MapPathFile(FileName);
long chunkSize = 204800; //指定塊大小
byte[] buffer = new byte[chunkSize]; //建立一個(gè)200K的緩沖區(qū)
long dataToRead = 0; //已讀的字節(jié)數(shù)
FileStream stream = null;
try
{
//打開文件
stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
dataToRead = stream.Length;
//添加Http頭
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(Path.GetFileName(filePath)));
HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString());
while (dataToRead > 0)
{
if (HttpContext.Current.Response.IsClientConnected)
{
int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Clear();
dataToRead -= length;
}
else
{
dataToRead = -1; //防止client失去連接
}
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("Error:" + ex.Message);
}
finally
{
if (stream != null) stream.Close();
HttpContext.Current.Response.Close();
}
}
/// <summary>
/// 輸出硬盤文件,提供下載 支持大文件、續(xù)傳、速度限制、資源占用小
/// </summary>
/// <param name="_Request">Page.Request對(duì)象</param>
/// <param name="_Response">Page.Response對(duì)象</param>
/// <param name="_fileName">下載文件名</param>
/// <param name="_fullPath">帶文件名下載路徑</param>
/// <param name="_speed">每秒允許下載的字節(jié)數(shù)</param>
/// <returns>返回是否成功</returns>
//---------------------------------------------------------------------
//調(diào)用:
// string FullPath=Server.MapPath("count.txt");
// ResponseFile(this.Request,this.Response,"count.txt",FullPath,100);
//---------------------------------------------------------------------
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;
int pack = 10240; //10K bytes
int sleep = (int)Math.Floor((double)(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((double)((fileLength - startBytes) / pack)) + 1;
for (int i = 0; i < maxCount; i++)
{
if (_Response.IsClientConnected)
{
_Response.BinaryWrite(br.ReadBytes(pack));
Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
return false;
}
return true;
}
}
asp.net下載文件的方法(二)
1 string fileName = "aaa.zip";//客戶端保存的文件名
2 string filePath = Server.MapPath("DownLoad/aaa.zip");//路徑
3
4 System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
5
6 if (fileInfo.Exists == true)
7 {
8 const long ChunkSize = 102400;//100K 每次讀取文件,只讀取100K,這樣可以緩解服務(wù)器的壓力
9 byte[] buffer = new byte[ChunkSize];
10
11 Response.Clear();
12 System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
13 long dataLengthToRead = iStream.Length;//獲取下載的文件總大小
14 Response.ContentType = "application/octet-stream";
15 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
16 while (dataLengthToRead > 0 && Response.IsClientConnected)
17 {
18 int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//讀取的大小
19 Response.OutputStream.Write(buffer, 0, lengthRead);
20 Response.Flush();
21 dataLengthToRead = dataLengthToRead - lengthRead;
22 }
23 Response.Close();
24 }