62,046
社区成员
发帖
与我相关
我的任务
分享
public class DownloadHandler : IHttpHandler
{
/// <summary>
/// 讀取文件
/// </summary>
/// <param name="filePath">文件路徑</param>
/// <param name="context">下載頁面</param>
/// <param name="downLoadType">下載類型</param>
private void ReadFile(string filePath,HttpContext context,string downLoadType)
{
try
{
using(FileStream fs= new FileStream(filePath,FileMode.Open,FileAccess.Read, FileShare.Read))
{
string fileName = Path.GetFileName(filePath);
string encodeFileName = HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(Path.GetFileNameWithoutExtension(filePath)));
string fileExtension = Path.GetExtension(filePath);
if(fileExtension == ".xls" && encodeFileName.Length > 215)
encodeFileName = encodeFileName.Substring(0,210);
context.Response.ClearContent();
context.Response.Clear();
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.AddHeader("Content-Length", fs.Length.ToString());
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", ""+downLoadType+"; filename=" + encodeFileName + fileExtension+"");
int readLength = 0;
byte[] buffer = new Byte[10240];//緩沖區大小 10k
while(true)
{
if(context.Response.IsClientConnected)
{
readLength = fs.Read(buffer,0,10240);
if(readLength == 0)break;
context.Response.OutputStream.Write(buffer, 0, readLength);
context.Response.Flush();
}
else
{
break;
}
}
context.Response.Close();
}
}
catch(Exception ex)
{
throw ex;
}
if(this.IsDelete){
DeleteFile(filePath);
}
}
private void DeleteFile(string filePath){
try{
if(System.IO.File.Exists(filePath)){
System.IO.File.Delete(filePath);
}
}
catch{}
}
private bool _isDelete;
private bool IsDelete{
get{return this._isDelete;}
}
public void ProcessRequest(HttpContext context)
{
if(context.Request["fn"] != null)
{
string filePath = Utils.Util.DecryptFileName(context.Request.QueryString["fn"].ToString().Trim()); //通过解密得到文件名
this._isDelete = context.Request.QueryString["d"] != null;
ReadFile(filePath,context,context.Request.QueryString["t"] == null ? "attachment" : "inline");//attachment:附件模式;inline在線模式
}
}
public bool IsReusable
{
get{return true;}
}
}