如果下载时直接通过访问文件的路径的方法,在下载.txt等文件时,浏览器会默认打开文件, 通过下面的方法,就可以避免浏览器打开文件,直接提示保存文件:
/// <summary>
/// 文件下载
/// </summary>
/// <param name="savename">保存时的文件名</param>
/// <param name="FullFileName">下载文件路径 Server.Mappath(filepath)</param>
/// <param name="Response">Response</param>
public static void savefile(string savename, string FullFileName, System.Web.HttpResponse Response)
{
try
{
FileInfo DownloadFile = new FileInfo(FullFileName);
if (DownloadFile.Exists)
{
Response.Clear();
Response.ClearHeaders();
Response.Buffer = false;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "p_w_upload;filename=" + System.Web.HttpUtility.UrlEncode(savename, System.Text.Encoding.UTF8));
Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
Response.TransmitFile(DownloadFile.FullName);
Response.Flush();
Response.End();
}
else
{
//文件不存在
}
}
catch
{
//文件不存在
}
}
/// 文件下载
/// </summary>
/// <param name="savename">保存时的文件名</param>
/// <param name="FullFileName">下载文件路径 Server.Mappath(filepath)</param>
/// <param name="Response">Response</param>
public static void savefile(string savename, string FullFileName, System.Web.HttpResponse Response)
{
try
{
FileInfo DownloadFile = new FileInfo(FullFileName);
if (DownloadFile.Exists)
{
Response.Clear();
Response.ClearHeaders();
Response.Buffer = false;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "p_w_upload;filename=" + System.Web.HttpUtility.UrlEncode(savename, System.Text.Encoding.UTF8));
Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
Response.TransmitFile(DownloadFile.FullName);
Response.Flush();
Response.End();
}
else
{
//文件不存在
}
}
catch
{
//文件不存在
}
}
转载于:https://blog.51cto.com/smilecong/187058