Asp.net下载文件
网站上的文件是临时文件, 浏览器下载完成, 网站需要将其删除.
下面的写法, 文件读写后没关闭, 经常删除失败.
/// <summary>
/// 下载服务器文件,参数一物理文件路径(含文件名称及后缀),参数二文件名称
/// </summary>
/// <param name="PhysicalPath"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static bool DownLoad(string PhysicalPath, string fileName)
{
bool _bool = false;
string[] arrSplit = PhysicalPath.Split('.'); string fileType = arrSplit[arrSplit.Length - ];//获得下载文件的类型
try
{
if ("xls".Equals(fileType))
{
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
}
//else if("xml".Equals(fileType))
//{
// HttpContext.Current.Response.ContentType = "application/octet-stream";
//}
else
{
HttpContext.Current.Response.ContentType = "application/x-zip-compressed";
} HttpContext.Current.Response.Charset = GlobalVar.ADMIN_CHARSET_ENCODING;
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Utils.UrlEncode(fileName));//设置文件名称
HttpContext.Current.Response.TransmitFile(PhysicalPath);
_bool = true;
}
catch
{ _bool = false;
}
finally
{
//发送到客户端的文件流,如果点击取消,此临时文件会一直打开着,无法快速删除,影响不大,之后再行解决
// HttpContext.Current.Response.Clear();
// HttpContext.Current.Response.Close();
} return _bool;
}
下面是正确写法, 解决用户点击取消, 临时文件还打开着的问题(down临时文件夹可不要)
/// <summary>
/// 下载服务器文件,参数一物理文件路径(含文件名称及后缀),参数二文件名称
/// </summary>
/// <param name="PhysicalPath"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static void DownLoad(string PhysicalPath, string NewFileName)
{
//清空下down目录下大于1小时的文件
string[] files = Directory.GetFiles(Utils.GetMapPath("down"));
foreach (string str in files)
{
FileInfo fileInfo = new FileInfo(str);
if (Math.Abs((fileInfo.CreationTime - DateTime.Now).TotalHours) > )
{
try
{
File.Delete(str);
}
catch
{
Func.SaveLog(, "删除" + str + "文件失败");
}
}
} //将要下载的文件复制到down临时文件夹
string strDownFileName = Path.Combine(Utils.GetMapPath("down"), new Random().Next(int.MaxValue).ToString());
File.Copy(PhysicalPath, strDownFileName, true); System.IO.Stream iStream = null; // Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[]; // Length of the file:
int length; // Total bytes to read:
long dataToRead; // Identify the file to download including its path.
string filepath = strDownFileName; // Identify the file name.
//string filename = System.IO.Path.GetFileName(filepath); try
{
// Open the file.
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read); // Total bytes to read:
dataToRead = iStream.Length; HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + Utils.UrlEncode(NewFileName)); // Read the bytes.
while (dataToRead > )
{
// Verify that the client is connected.
if (HttpContext.Current.Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, , ); // Write the data to the current output stream.
HttpContext.Current.Response.OutputStream.Write(buffer, , length); // Flush the data to the HTML output.
HttpContext.Current.Response.Flush(); buffer = new Byte[];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -;
}
}
}
catch (Exception ex)
{
// Trap the error, if any.
HttpContext.Current.Response.Write("Error : " + ex.Message);
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
}
}
Asp.net下载文件的更多相关文章
- Asp.Net 下载文件的几种方式
asp.net下载文件几种方式 protected void Button1_Click(object sender, EventArgs e) { /* 微软为Response对象提供了一个新的方法 ...
- asp.net下载文件几种方式
测试时我以字符流的形式下载文件,可行,前几个仅作参考 protected void Button1_Click(object sender, EventArgs e) { /* 微软为Respo ...
- asp.net 下载文件(图片、word、excel等)
string filePath = Server.MapPath("~/excel.xlsx"); if (File.Exists(filePath)) { FileStream ...
- ASP.NET 下载文件方式
protected void Button1_Click(object sender, EventArgs e) { /* 微软为Response对象提供了一个新的方法TransmitFile来解决使 ...
- asp.net 下载文件几种方式
protected void Button1_Click(object sender, EventArgs e) { /* 微软为Response对象提供了一个新的方法TransmitFile来解决使 ...
- ASP.NET 下载文件并继续执行JS解决方法
需求说明:当用户点击按钮时使当前按钮为不可用,并打开新页面,关闭新页面时,按钮变为可用.并且如果不关闭新页面,当前按钮过10秒钟自动变为可用. 包含3个页面: 一.按钮页 前台代码:当刷新后采用js进 ...
- asp.net下载文件方法
/// <summary> /// 下载 /// </summary> /// <param name="url"></param> ...
- asp.net下载文件的几种方法
最近做东西遇到了下载相关的问题.在这里总结一下自己处理的方法. 1.以字节流的形式向页面输出数据以下载Excel为例子. string path=Server.MapPath("文件路径&q ...
- 解决用ASP.NET下载文件时,文件名为乱码的问题
关键就一句: string strTemp = System.Web.HttpUtility.UrlEncode(strName, System.Text.Enc ...
随机推荐
- OC—设计模式-通知的使用
通知 通知(广播) 可以一对多的发送通知(一个发送者 多个观察者) 特别注意:在发送者 发送通知的时候,必须有观察者 发送者,就是注册一个通知中心,以他为中心,发送消息 通过通知的名字,来判断是哪个通 ...
- HackerRank "Minimum Average Waiting Time" !
Something to learn: http://blog.csdn.net/yuwenshi/article/details/36666453 Shortest Job First Algori ...
- SPOJ #11 Factorial
Counting trailing 0s of n! It is not very hard to figure out how to count it - simply count how many ...
- Hadoop:使用原生python编写MapReduce
功能实现 功能:统计文本文件中所有单词出现的频率功能. 下面是要统计的文本文件 [/root/hadooptest/input.txt] foo foo quux labs foo bar quux ...
- Windows2012修改光驱盘符
1.输入diskmgmt.msc打开磁盘管理器 2.找到需要修改的盘符,右键点击修改盘符
- 使用mongo-java-driver3.0.2.jar和mongodb3.0在java代码中的用户验证4
以下是使用mongo-java-driver3.0.2.jar和mongodb3.0.4在java代码中的用户验证: ServerAddress sa = new ServerAddress(host ...
- SQL语句技巧_索引的优化_慢查询日志开启_root密码的破解
1.正则表达式的使用 regexp例:select name,email from t where email regexp '@163[.,]com$'使用like方式查询selct name,em ...
- mysql_connect和mysql_pconnect区别(转)
php中mysql_pconnect()的实现方式:其实mysql_pconnect()本身并没有做太多的处理,它唯一做的只是在php运行结束后不主动close掉mysql的连接.mysql_pcon ...
- div里面的内容超出自身高度时,显示省略号
1.给DIV设置属性:width: 200px; text-overflow: ellipsis; overflow: hidden; 当div里面的内容总宽度找过 200PX的时候,超出的部分会以“ ...
- HDU 2717 Catch That Cow(BFS)
Catch That Cow Farmer John has been informed of the location of a fugitive cow and wants to catch he ...