ASP.NET直接下载一个文件和打开一个文件

//下载一个文件
string ConnStr=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
 string str_get_file="select * from fmfilecont where fileid=9";
 SqlConnection Conn = new SqlConnection(ConnStr);
SqlCommand myCommand=new SqlCommand(str_get_file,Conn);
Conn.Open();
SqlDataReader dr =myCommand.ExecuteReader();
if (dr.Read())
{ string filename=dr["fname"].ToString();
 Response.Buffer=true;
 Response.Clear();
 Response.ContentType="+dr[ftype]+"; //读取文件类型
 Page.Response.AddHeader("Content-Disposition","attachment; filename=" + HttpUtility.UrlEncode(filename));
//当要下载的文件名是中文时,需加上HttpUtility.UrlEncode
 byte[] file=(byte[])dr["cont"];
//数据库中存文件的字段,数据类型是image
Response.BinaryWrite(file);
Response.Flush();
Response.End();

// 直接打开一个文件
int id= Convert.ToInt32( Request.QueryString["docId"],10);
     string ConnStr=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
    string str_get_file="select * from fmfilecont where fileid="+id;
    SqlConnection Conn = new SqlConnection(ConnStr);
    SqlCommand myCommand=new SqlCommand(str_get_file,Conn);
    Conn.Open();

    SqlDataReader dr = myCommand.ExecuteReader();

    if(dr.Read())
    {
     Response.ContentType = (string)dr["ftype"];
     Response.OutputStream.Write((byte[])dr["cont"], 0, (int)dr["Size"]);
    }
    else
    {
     Response.Write("没有这个文件");
     Response.End();
    }

    dr.Close();
    myCommand.Connection.Close();

posted @ 2005-08-11 09:18  编程入门  阅读(6238)  评论(1编辑  收藏  举报