图像从SQL Server表到asp.net图像控件

时间:2012-10-12 06:55:08

标签: c# asp.net sql-server-2008 ado.net

SqlCommand cmd = new SqlCommand("select top 1(CMTID),COMMENT,HEADING from FTAB ORDER BY CMTID DESC", conn);
conn.Open();

SqlDataReader sdr = cmd.ExecuteReader();

if (sdr.Read() == true)
{
    lblHead.Text = sdr["HEADING"].ToString();
    lblData.Text = sdr["COMMENT"].ToString();

}

conn.Close();

这是从表中检索正常数据值的代码现在我想从SQL Server获取保存为底部代码提及的Binary数据的图片。所以我想将图片检索到asp.net的Image控件中;请指导我。

if (FileUpload1.HasFile)
{
        conn.Close();

        String SqlQery;
        SqlQery = "select max(CMTID) from FTAB";

        SqlCommand cmdid = new SqlCommand(SqlQery, conn);
        conn.Open();

        MaxID = (int)(cmdid.ExecuteScalar()) + 1;

        conn.Close();

        byte[] img = new byte[FileUpload1.PostedFile.ContentLength];
        HttpPostedFile myimg = FileUpload1.PostedFile;
        myimg.InputStream.Read(img, 0, FileUpload1.PostedFile.ContentLength);
        SqlCommand cmd = new SqlCommand("insert into FTAB (CMTID, IMAGEDT, COMMENT, DATETM, HEADING) values (@imgid, @image, @comment, @datetm, @heading)", conn);

        SqlParameter imgid = new SqlParameter("@imgid",SqlDbType.Int);
        imgid.Value = MaxID;
        cmd.Parameters.Add(imgid);

        SqlParameter uploading = new SqlParameter("@image", SqlDbType.Image);
        uploading.Value = img;
        cmd.Parameters.Add(uploading);

        SqlParameter cmtt = new SqlParameter("@comment", SqlDbType.NVarChar);
        cmtt.Value = RadTextBox3.Text;
        cmd.Parameters.Add(cmtt);

        SqlParameter dttm = new SqlParameter("@datetm", SqlDbType.DateTime);
        dttm.Value = DateTime.Now;
        cmd.Parameters.Add(dttm);

        SqlParameter hhding = new SqlParameter("@heading", SqlDbType.NVarChar);
        hhding.Value = RadTextBox8.Text;
        cmd.Parameters.Add(hhding);

        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();

        lblHead.Text = "Image uploaded";
    }
    else
    {
        lblHead.Text = "No file selected";
    }

2 个答案:

答案 0 :(得分:1)

试试这个

SqlCommand cmd = new SqlCommand("select IMAGEDT from FTAB", new SqlConnection("your connection string"));
object data = cmd.ExecuteScalar();
byte[] imgBytes = (byte[])data;

System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();

string filePath = Server.MapPath("temp") + "//" + "img"+DateTime.Now.Ticks.ToString()+".png";
FileStream fs = File.Create(filePath);
fs.Write(imgBytes, 0, imgBytes.Length);
fs.Flush();
fs.Close();

img.ImageUrl = filePath;

但我想说这不是最好的方法,您应该将上传的图像保存为您网站中的文件,并将该文件的路径保存在数据库中。

答案 1 :(得分:0)

yogi的答案原则上是正确的,但需要一个Web服务器目录“temp”并对IIS目录进行写访问。

您也可以使用image handler as explained in another SO question解决问题。数据库检索以相同的方式完成,但渲染是从流而不是临时文件进行的。