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 ...
随机推荐
- HackerRank "Favorite sequence"
Typical topological sorting problem .. why is it 'difficult'? #include <iostream> #include < ...
- 剑指offer系列55---最小的k个数
[题目] 输入n个整数,找出其中最小的K个数.例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,. *[思路]排序,去除k后的数. package com.exe11 ...
- 基于.net开发chrome核心浏览器
本文转载自:http://www.cnblogs.com/liulun/archive/2013/04/20/3031502.html 一: 上一篇的链接: 基于.net开发chrome核心浏览器[一 ...
- Redis性能测试工具benchmark简介
Redis自己提供了一个性能测试工具redis-benchmark.redis-benchmark可以模拟N个机器,同时发送M个请求. 用法:redis-benchmark [-h -h <ho ...
- css 默认
先写全局的样式 body { margin:0 auto; font-size:12px; font-family:Verdana; line-height:1.5;} ul,dl,dd,h1,h2, ...
- 利用MyEclipse自动创建PO类、hbm文件(映射文件)、DAO
原文地址:http://blog.csdn.net/fangzhibin4712/article/details/7179414 前提条件:表sjzdfl 表sjzdxx (使用数据库MySQL) ...
- 【VB技巧】VB ListView 控件功能使用详解
来源:http://lcx.cc/?i=494 ListView控件 在工具箱上击鼠标右键,选择快捷菜单的Components(部件)项,在控件列表中选择Microsoft Windows Commo ...
- asp.net和脚本获取当前的URL、IP地址
介绍一下ASP.NET取得当前页面的完整URL 的方放,icech做成了函数,直接用吧! private string GetPath() { string strPath = "http: ...
- ASP.NET内置对象详解
ASP.NET的内置对象介绍 1.Response 2.Request 3.Server 4.Application 5.Session 6.Cookie Request对象主要是让服务器取得客户端浏 ...
- \r\n的坑
\r回车符 \n换行符 由于历史原因,windows下的换行符为\r\n linux或者html等开源或公开标准的换行符是\n ---- 为什么windows下的回车换行是\r\n? 第一台打印机,每 ...