C#文件下载实例代码(适用于各个浏览器)
程序员文章站
2023-10-22 15:40:46
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#文件下载实例代码(适用于各个浏览器),希望对大家有所帮助
上一篇: C#使用NOPI库实现导入Excel文档