最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
如何把数据放到web不能访问的文件夹中并给用户下载?
时间:2022-07-02 23:35:33 编辑:袖梨 来源:一聚教程网
在应用中我们可能遇到这样的情况,我们需要临时生成一个数据文件给用户下载,但是每次下载都要判断,也就是说,用户并不能得到这个下载的url不断下载文件,下面是实现方法。文件保存为csv格式,方便数据导入导出,基本原理就是用流写入文件然后用Response.WriteFile把流发送到客户端。
表的结构同此文:http://blog.111com.net/lovecherry/archive/2005/02/25/301441.aspx
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
SqlDataAdapter da=new SqlDataAdapter("select * from tb1",conn);
DataSet ds=new DataSet();
da.Fill(ds,"table1");
DataTable dt=ds.Tables["table1"];
string name=System.Configuration.ConfigurationSettings.AppSettings["downloadurl"].ToString()+DateTime.Today.ToString("yyyyMMdd")+new Random(DateTime.Now.Millisecond).Next(10000).ToString()+".csv";//存放到web.config中downloadurl指定的路径,文件格式为当前日期+4位随机数
FileStream fs=new FileStream(name,FileMode.Create,FileAccess.Write);
StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
sw.WriteLine("自动编号,姓名,年龄");
foreach(DataRow dr in dt.Rows)
{
sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);
}
sw.Close();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.WriteFile(name); // 把文件流发送到客户端
Response.End();
在这段代码前面你可以放置一些判断,判断是不是这个用户可以下载文件,生成的文件可以把名字存放到数据库中,下次可以直接下载而不要重复写文件了。
表的结构同此文:http://blog.111com.net/lovecherry/archive/2005/02/25/301441.aspx
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
SqlDataAdapter da=new SqlDataAdapter("select * from tb1",conn);
DataSet ds=new DataSet();
da.Fill(ds,"table1");
DataTable dt=ds.Tables["table1"];
string name=System.Configuration.ConfigurationSettings.AppSettings["downloadurl"].ToString()+DateTime.Today.ToString("yyyyMMdd")+new Random(DateTime.Now.Millisecond).Next(10000).ToString()+".csv";//存放到web.config中downloadurl指定的路径,文件格式为当前日期+4位随机数
FileStream fs=new FileStream(name,FileMode.Create,FileAccess.Write);
StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
sw.WriteLine("自动编号,姓名,年龄");
foreach(DataRow dr in dt.Rows)
{
sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);
}
sw.Close();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.WriteFile(name); // 把文件流发送到客户端
Response.End();
在这段代码前面你可以放置一些判断,判断是不是这个用户可以下载文件,生成的文件可以把名字存放到数据库中,下次可以直接下载而不要重复写文件了。
相关文章
- 《QQ》情侣空间历史情侣查看方法 08-02
- win11系统防火墙在哪里关闭?win11关闭防火墙和杀毒软件方法 08-02
- 澳大利亚证券投资委员会警告Bitget在澳提供“未经许可”的高杠杆加密货币期货产品 08-02
- 《怪兽大联盟》开荒推图阵容推荐 08-02
- win11自带的应用商店不能用为什么 win11无法打开应用商店如何解决 08-02
- 《QQ》资料卡背景封面设置方法 08-02