public class FileDownLoad
{
/// <summary>
/// 通用下载函数
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="filePath">文件路径</param>
public static bool DownLoadFile(string fileName, string filePath)
{
if (File.Exists(filePath))
{
FileInfo file = new FileInfo(filePath);
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //解决中文乱码
string fileExtension = System.IO.Path.GetExtension(System.IO.Path.GetFileName(filePath));//文件扩展名
if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("msie") > -1)
{
//当客户端使用IE时,对其进行编码;
//使用 ToHexString 代替传统的 UrlEncode();
fileName = ToHexString(fileName);
}
if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("firefox") > -1)
{
//为了向客户端输出空格,需要在当客户端使用 Firefox 时特殊处理
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
}
else
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
HttpContext.Current.Response.AddHeader("Content-length", file.Length.ToString());
HttpContext.Current.Response.ContentType = "appliction/octet-stream";
HttpContext.Current.Response.WriteFile(file.FullName);
HttpContext.Current.Response.End();
return true;
}
else
{
HttpContext.Current.Response.Write("<script language=javascript>alert('下载失败,此文件已被删除!');</script>");
return false;
}
}
#region 编码
/// <summary>
/// 对字符串中的非 ASCII 字符进行编码
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string ToHexString(string s)
{
char[] chars = s.ToCharArray();
StringBuilder builder = new StringBuilder();
for (int index = 0; index < chars.Length; index++)
{
bool needToEncode = NeedToEncode(chars[index]);
if (needToEncode)
{
string encodedString = ToHexString(chars[index]);
builder.Append(encodedString);
}
else
{
builder.Append(chars[index]);
}
}
return builder.ToString();
}
/// <summary>
/// 判断字符是否需要使用特殊的 ToHexString 的编码方式
/// </summary>
/// <param name="chr"></param>
/// <returns></returns>
private static bool NeedToEncode(char chr)
{
string reservedChars = "$-_.+!*'(),@=&";
if (chr > 127)
return true;
if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0)
return false;
return true;
}
/// <summary>
/// 为非 ASCII 字符编码
/// </summary>
/// <param name="chr"></param>
/// <returns></returns>
private static string ToHexString(char chr)
{
UTF8Encoding utf8 = new UTF8Encoding();
byte[] encodedBytes = utf8.GetBytes(chr.ToString());
StringBuilder builder = new StringBuilder();
for (int index = 0; index < encodedBytes.Length; index++)
{
builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16));
}
return builder.ToString();
}
#endregion
}