System.Web.HttpPostedFile upfile=this.File1.PostedFile;
int length=upfile.ContentLength;
try
{
if(length==0)
{
this.Label1.Text="请选择您上传的文件";
}
else
{
byte[] fileByteArr=new byte[length];
Stream streamObject =upfile.InputStream;
streamObject.Read(fileByteArr,0,length);
string strCon="server=localhost;uid=sa;password=123;database=northwind";
SqlConnection cn= new  SqlConnection(strCon);
string sql="insert into images(data,contenttype,description,imagesize) values('{0}','{1}','{2}','{3}')";
string sqlInsert=string.Format(sql,fileByteArr,upfile.ContentType,this.TextBox1.Text.ToString(),length);
SqlCommand cmd=new SqlCommand(sqlInsert,cn);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
this.Label1.Text="上传成功";
}
}
catch(Exception ex)
{
this.Label1.Text=ex.Message.ToString(); }但是我的fileByteArr好像是空的
请问为什么啊,如何修改啊

解决方案 »

  1.   

    string sql="insert into images(data,contenttype,description,imagesize) values('{0}','{1}','{2}','{3}')";
    string sqlInsert=string.Format(sql,fileByteArr,upfile.ContentType,this.TextBox1.Text.ToString(),length);
    SqlCommand cmd=new SqlCommand(sqlInsert,cn);
    这样是不行的,这种方式只能用来处理字符串,要用Parameter
       string sql="insert into images(data) values(@data)";
              
                System.Data.SqlClient.SqlCommand cmd=new SqlCommand(sqlInsert,cn);
                cmd.Parameters.Add("@data",System.Data.SqlDbType.Image);
                cmd.Parameters["@data"].Value = fileByteArr;
      

  2.   

    改称System.Data.SqlClient.SqlCommand cmd=new SqlCommand(sqlInsert,cn);
                cmd.Parameters.Add("@data",System.Data.SqlDbType.Image);
                cmd.Parameters["@data"].Value = fileByteArr;
    这种方法存到数据库里的为什么是<Binary>,这样使正确的么
    还有我用这种方法读出来为什么显示System.Byte[]这个
    string strCon="server=localhost;uid=sa;password=123;database=northwind";
    SqlConnection cn= new  SqlConnection(strCon);
    string sql="select * from images where id=1";
    SqlCommand cmd=new SqlCommand(sql,cn);
    cmd.Connection.Open();
    SqlDataReader dr=cmd.ExecuteReader();
    if(dr.Read())
    {
    Response.ContentType=dr["contenttype"].ToString();
    Response.OutputStream.Write((byte[])dr["data"],0,(int)dr["imagesize"]);
    }
    dr.Close();
    cmd.Connection.Close()