using System.Data;
using System.Linq;
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 System.Xml.Linq;
using System.Text;
using System.IO;
namespace DownLoad{
public class Download
{
/// <summary>
/// 下载文件
/// </summary>
/// <param name="downloadFilePath">被下载文件的路径,相对和绝对都可以</param>
/// <param name="showFileName">显示给用户的文件名,可以为空</param>
public static void DownloadDataByNew(string downloadFilePath, string showFileName)
{
showFileName = showFileName.Replace("\"", "”");
downloadFilePath = (downloadFilePath ?? "").Trim();
string saveFileName;
if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("msie") > -1)
{
saveFileName = HttpUtility.UrlEncode(showFileName);
}
else if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("firefox") > -1)
{
saveFileName = showFileName;
}
else
{
saveFileName = HttpUtility.UrlPathEncode(showFileName);
}
if (downloadFilePath.IndexOf(":") < 0)
downloadFilePath = System.Web.HttpContext.Current.Server.MapPath(downloadFilePath);
showFileName = showFileName.Trim();
if (string.Empty == showFileName)
showFileName = Path.GetFileName(downloadFilePath);
Stream objStream = null;
byte[] btBuffer = new byte[10240]; // 1024*8 = 8Kb
int intLength = 0;
long lngData2Read = 0;
try
{
using (objStream = new FileStream(downloadFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
lngData2Read = objStream.Length;
System.Web.HttpContext.Current.Response.Clear();
#region 输出HTTP头信息
System.Web.HttpContext.Current.Response.AddHeader("Content-Length", (lngData2Read).ToString());
System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + saveFileName.Replace("+", "%20"));
#endregion
btBuffer = new byte[10240];
while (lngData2Read > 0)
{
if (HttpContext.Current.Response.IsClientConnected)
{
intLength = objStream.Read(btBuffer, 0, 10240);
HttpContext.Current.Response.OutputStream.Write(btBuffer, 0, intLength);
HttpContext.Current.Response.Flush();
lngData2Read -= intLength;
}
else
{
lngData2Read = -1;
}
}
}
}
catch (Exception ex)
{
}
HttpContext.Current.Response.End();
}
}
}