zoukankan      html  css  js  c++  java
  • (原创)如何把数据放到web不能访问的文件夹中并给用户下载?

    在应用中我们可能遇到这样的情况,我们需要临时生成一个数据文件给用户下载,但是每次下载都要判断,也就是说,用户并不能得到这个下载的url不断下载文件,下面是实现方法。文件保存为csv格式,方便数据导入导出,基本原理就是用流写入文件然后用Response.WriteFile把流发送到客户端。
    表的结构同此文:http://www.cnblogs.com/lovecherry/archive/2005/03/25/125487.html


    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();

    在这段代码前面你可以放置一些判断,判断是不是这个用户可以下载文件,生成的文件可以把名字存放到数据库中,下次可以直接下载而不要重复写文件了。
  • 相关阅读:
    java邮箱发送
    mybaties xml 的头部
    eclipse启动报.log错误
    【高性能网站搭建-learn-web-vitals翻译】——Web Vitals
    【高性能网站搭建-learn-web-vitals翻译】——开篇
    git提交代码步骤以及工作中常用的git命令
    苹果手机focus没有效果 键盘跳不出来
    MVC,MVP与MVVM
    媒体查询用法及常见媒体尺寸
    浏览器内核
  • 原文地址:https://www.cnblogs.com/lovecherry/p/125489.html
Copyright © 2011-2022 走看看