当前位置: 移动技术网 > IT编程>开发语言>c# > C#文件下载实例代码(适用于各个浏览器)

C#文件下载实例代码(适用于各个浏览器)

2019年07月18日  | 移动技术网IT编程  | 我要评论
1、cs代码 public void downfile(string filepath ,string filename ) { // filepath 文

1、cs代码

public void downfile(string filepath ,string filename )
{
 // filepath 文件路径 例如:/file/记录.xlsx 
 // filename 文件名称 例如:记录.xlsx (要后缀哦)
encoding encoding; // 申明编码
string outputfilename; // 输出名字
debug.assert(httpcontext.applicationinstance.request.useragent != null, "httpcontext.applicationinstance.request.useragent != null");
string browser = httpcontext.applicationinstance.request.useragent.toupper();
// 微软的浏览器和ie过滤
if (browser.contains("ms") && browser.contains("ie"))
{
outputfilename = httputility.urlencode(filepath);
encoding = encoding.default;
}
//火狐
else if (browser.contains("firefox"))
{
outputfilename = filename;
encoding = encoding.getencoding("gb2312");
}
else
{
outputfilename = httputility.urlencode(filename);
encoding = encoding.default;
}
string absolufilepath = server.mappath(filepath); //获取上传文件路径
filestream fs = new filestream(absolufilepath, filemode.open);
byte[] bytes = new byte[(int)fs.length];
fs.read(bytes, 0, bytes.length);
fs.close(); //关闭流,释放资源
httpcontext.applicationinstance.response.clear();
httpcontext.applicationinstance.response.buffer = true;
httpcontext.applicationinstance.response.contentencoding = encoding;
httpcontext.applicationinstance.response.addheader("content-disposition", string.format("attachment; filename={0}", string.isnullorempty(outputfilename) ? datetime.now.tostring("yyyymmddhhmmssfff") : outputfilename));
response.binarywrite(bytes);
response.flush();
httpcontext.applicationinstance.response.end();
}

2、html代码

前端html 写一个a标签就好:如 <a href='downfile' target='_blank'>文件下载</a>

以上所述是小编给大家介绍的c#文件下载实例代码(适用于各个浏览器),希望对大家有所帮助

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网