图片以二进制的方式存入数据库,以及取出图片

 protected void saveimage_Click(object sender, EventArgs e)
    {
        #region 把图片以二进制的形式存入数据库
        Stream imageStream;
        string path = fileupload.PostedFile.FileName;//文件名
        int size = fileupload.PostedFile.ContentLength;//文件大小
        string type = fileupload.PostedFile.ContentType;//文件类型
        imageStream = fileupload.PostedFile.InputStream;
        byte[] content = new byte[size];
        //=Request.QueryString["name"];
        string name = this.name.Text.Trim();
        int status = imageStream.Read(content, 0, size);
        string sql = "insert into pacture (image,name)values(@image,@name) ";
        SqlParameter[] pams = {
                              new SqlParameter("@image",content),
                              new SqlParameter("@name",name)
                              };
        int i = ExecuteNonQuery(sql, pams);
        if (i > 0)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), null, "alert('成功!')", true);
        }
        else
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), null, "alert('失败!')", true);
        }
        #endregion
    }

此方法中:image字段的数据类型应为image

 

  protected void getimage_Click(object sender, EventArgs e)
    {
        string sql = "select * from pacture";
        DataTable dt = ExecuteDataTable(sql, null);
        byte[] bt=null;
        if (dt.Rows.Count > 0)
        {
            bt = (byte[])dt.Rows[0][1];
        }
        #region 把图片输出到指定目录
        FileStream fs = new FileStream(@"H:\1.jpg", FileMode.Create, FileAccess.Write);
        fs.Write(bt, 0, bt.Length);
        fs.Flush();
        fs.Close();
        #endregion
        #region 把图片显示在网页
        //Response.ContentType = "application/octet-stream";
        //Response.BinaryWrite(bt);
        //Response.End();
        #endregion
    }

posted @ 2012-07-20 14:51  cbwbin  阅读(1125)  评论(0编辑  收藏  举报