protected void download(object sender, EventArgs e)
    {
        string tableName = "tbl_attach";
        string filedesc = "filedesc";
        string strConn = "server=.;database=web;uid=sa;pwd=rezin";
        SqlConnection cn = new SqlConnection(strConn);
        SqlCommand cm = new SqlCommand();
        cm.Connection = cn;
        cm.CommandType = CommandType.Text;
        if (cn.State == 0)
        {
            cn.Open();
        }
        cm.CommandText = "select " + filedesc + " from " + tableName + " where attachid=5";
        //SqlDataReader results = cm.ExecuteReader();
        //客户端保存的文件名
        string fileName = "bbb.zip";
        //下载路径
        string filePath = Server.MapPath("Download/aaa.txt");
        //以字符流的形式下载文件
        FileStream fs = new FileStream(filePath, FileMode.Open);
        byte[] bytes = new byte[(int)fs.Length];
        fs.Read(bytes, 0, bytes.Length);
        fs.Close();
        Response.ContentType = "application/octet-stream";
        //通知浏览器下载文件而不是打开
        Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
        Response.BinaryWrite(bytes);
        Response.Flush();
        Response.End();
    }  
新手,在网上参考的代码,我想知道怎么下载从数据库取出的文件名,用cm.CommandText下载的是sql(cm.CommandText = "select " + filedesc + " from " + tableName + " where attachid=5";)语句,怎样才能显示为查询出来的文件名,还有string fileName = "bbb.zip";下载文件名怎么显示为默认的名字!谢谢!

解决方案 »

  1.   


    /// <summary>
        /// 执行查询语句,返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }调用:
    string sql="";
    DataTable dt =new DataTable();
    dt=Query(sql).Table[0];