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 ...
随机推荐
- C#与JAVA平台RSA算法交互示例
很久以前的文章中,演示了如何对于.net和win32下面的delphi的RSA互操作性的实现,对于C#和JAVA之前的RSA加密解密也是很简单的,一般都采用了标准的规范,所以在互操作性方面是很方便的. ...
- 03 在Linux下安装Myeclipse及Tomcat(含下载)
测试环境: 主机系统:Win 7 虚拟机:VMware workstation 11.1.0 虚拟机OS: centos 6.5 64位 Kernel 2.6.32-431-e16.x86_64 My ...
- SSH_框架整合7--整个项目CODE
一 架构 1Action类 2 配置文件 3 View页面 二 Code 1 src (1)com.atguigu.ssh.actions >EmployeeAction.java packa ...
- Spring实战6:利用Spring和JDBC访问数据库
主要内容 定义Spring的数据访问支持 配置数据库资源 使用Spring提供的JDBC模板 写在前面:经过上一篇文章的学习,我们掌握了如何写web应用的控制器层,不过由于只定义了SpitterRep ...
- 拿nodejs快速搭建简单Oauth认证和restful API server攻略
拿nodejs快速搭建简单Oauth认证和restful API server攻略:http://blog.csdn.net/zhaoweitco/article/details/21708955 最 ...
- 请使用-Xlint:deprecation重新编译
[已解决]Android Studio编译OsmAnd出现警告:GeoPointParserUtil.java使用或覆盖了已过时的 API.有关详细信息请使用-Xlint:deprecation重新编 ...
- MEF简单示例
原文地址: http://www.cnblogs.com/xiaokang088/archive/2012/02/21/2361631.html MEF 的精髓在于插件式开发,方便扩展. 例如,应用程 ...
- NeHe OpenGL教程 第一课:OpenGL窗口
转自[翻译]NeHe OpenGL 教程 前言 声明,此 NeHe OpenGL教程系列文章由51博客yarin翻译(2010-08-19),本博客为转载并稍加整理与修改.对NeHe的OpenGL管线 ...
- HTML5与HTML4的区别
一.推出的理由及目标 web浏览器之间的兼容性很低 文档结构不够明确 web应用程序的功能受到了限制 二.语法的改变 内容类型 文件扩展名html htm 内容类型 texthtml 二者不变 ...
- apache配置常用模块
需要加载的模块列表 LoadModule php5_module modules/libphp5.so LoadModule actions_module modules/mod_actions.so ...