62,046
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 下载指定路径文件
/// </summary>
/// <param name="path">文件绝对路径</param>
public static void DownLoadFile(string path, string oldFileName)
{
System.IO.FileInfo fi = new System.IO.FileInfo(path);
if (fi.Exists)
{
//判断文件是否正在使用
try
{
using (System.IO.FileStream fs = System.IO.File.Open(path, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.None))
{
}
}
catch (Exception)
{
throw;
}
if (string.IsNullOrEmpty(oldFileName))
oldFileName = path.Substring(path.LastIndexOf("\\") + 1);
string browser = System.Web.HttpContext.Current.Request.UserAgent.ToUpper();
if (browser.Contains("FIREFOX") == true)
oldFileName = "\"" + oldFileName + "\"";
else if (browser.Contains("MSIE"))
oldFileName = ToHexString(oldFileName);
else
oldFileName = HttpUtility.UrlEncode(oldFileName);
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + oldFileName);
System.Web.HttpContext.Current.Response.AddHeader("Content-Length", fi.Length.ToString());
System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream;charset=gb2321";
System.Web.HttpContext.Current.Response.WriteFile(fi.FullName);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.Close();
}
else
{
throw new Exception("文件在服务器上不存在!");
}
}
#region 下载指定路径文件
/// <summary>
/// 下载指定路径文件
/// </summary>
/// <param name="path">文件绝对路径</param>
public static void DownLoadFile(string path, string oldFileName)
{
System.IO.FileInfo fi = new System.IO.FileInfo(path);
if (fi.Exists)
{
//判断文件是否正在使用
try
{
using (System.IO.FileStream fs = System.IO.File.Open(path, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.None))
{
}
}
catch (Exception)
{
throw;
}
if (string.IsNullOrEmpty(oldFileName))
oldFileName = path.Substring(path.LastIndexOf("\\") + 1);
string browser = System.Web.HttpContext.Current.Request.UserAgent.ToUpper();
if (browser.Contains("FIREFOX") == true)
oldFileName = "\"" + oldFileName + "\"";
else if (browser.Contains("MSIE"))
oldFileName = ToHexString(oldFileName);
else
oldFileName = HttpUtility.UrlEncode(oldFileName, System.Text.Encoding.UTF8);
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.AppendHeader("Content-Encoding", "no");//解决服务器启用gizp后文件下载出错问题
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + oldFileName);
System.Web.HttpContext.Current.Response.AddHeader("Content-Length", fi.Length.ToString());
System.Web.HttpContext.Current.Response.TransmitFile(fi.FullName);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.Close();
}
else
{
throw new Exception("文件在服务器上不存在!");
}
}
/// <summary>
/// 为字符串中的非英文字符编码
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string ToHexString(string s)
{
char[] chars = s.ToCharArray();
System.Text.StringBuilder builder = new System.Text.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>
///指定 一个字符是否应该被编码
/// </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>
/// 为非英文字符串编码
/// </summary>
/// <param name="chr"></param>
/// <returns></returns>
private static string ToHexString(char chr)
{
System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();
byte[] encodedBytes = utf8.GetBytes(chr.ToString());
System.Text.StringBuilder builder = new System.Text.StringBuilder();
for (int index = 0; index < encodedBytes.Length; index++)
{
builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16));
}
return builder.ToString();
}
#endregion
/// <summary>
/// 为字符串中的非英文字符编码
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string ToHexString(string s)
{
char[] chars = s.ToCharArray();
System.Text.StringBuilder builder = new System.Text.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>
///指定 一个字符是否应该被编码
/// </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>
/// 为非英文字符串编码
/// </summary>
/// <param name="chr"></param>
/// <returns></returns>
private static string ToHexString(char chr)
{
System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();
byte[] encodedBytes = utf8.GetBytes(chr.ToString());
System.Text.StringBuilder builder = new System.Text.StringBuilder();
for (int index = 0; index < encodedBytes.Length; index++)
{
builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16));
}
return builder.ToString();
}
public static void ResponseApplicationFile(this HttpContext context, string filePath, string saveAsName, bool isDirectOpen = false)
{
HttpResponse Response = context.Response;
Response.Clear();
Response.Buffer = true;
Response.ContentType = MIMEUtility.GetMIMEType(filePath);
string downloadFileSaveAsName = string.Empty;
if (string.IsNullOrWhiteSpace(System.IO.Path.GetFileNameWithoutExtension(saveAsName)) || string.IsNullOrWhiteSpace(saveAsName))
{
downloadFileSaveAsName = System.IO.Path.GetFileName(filePath);
}
else if (System.IO.Path.GetExtension(filePath).ToUpper() == System.IO.Path.GetExtension(saveAsName))
{
downloadFileSaveAsName = saveAsName;
}
else
{
downloadFileSaveAsName = saveAsName + System.IO.Path.GetExtension(filePath);
}
Response.HeaderEncoding = Encoding.UTF8;
if (System.IO.File.Exists(filePath))
{
Response.AddHeader("content-disposition", (isDirectOpen ? "" : "attachment;") + " filename=" + HttpUtility.UrlEncode(downloadFileSaveAsName, Encoding.UTF8) + ";size=" + (new FileInfo(filePath)).Length.ToString());
byte[] contents = System.IO.File.ReadAllBytes(filePath);
Response.BinaryWrite(contents);
}
else
{
Response.AddHeader("content-disposition", (isDirectOpen ? "" : "attachment;") + "filename=" + HttpUtility.UrlEncode(downloadFileSaveAsName, Encoding.UTF8) + ";size=0");
}
Response.Flush();
Response.End();
}
然后这样调用:
protected void Page_Load(object sender, EventArgs e)
{
this.Button_DownloadTemplateFile.Click += new EventHandler(Button_DownloadTemplateFile_Click);
}
void Button_DownloadTemplateFile_Click(object sender, EventArgs e)
{
string filename = "xxxxxx.xls";
string DownloadFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory+EnvironmentSetting.ThankyouLetterPath, filename);
if (!System.IO.File.Exists(DownloadFilePath))
{
this.MessageBoxLayer.Show("找不到相關檔案");
return;
}
byte[] contents = System.IO.File.ReadAllBytes(DownloadFilePath);
FileInfo info = new FileInfo(DownloadFilePath);
long fileSize = info.Length;
this.Context.ResponseApplicationFile(DownloadFilePath, filename);
}