2012-10-12 85 views
0
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(); 

這對正常的數據值的代碼從表中檢索現在我想從被保存爲Binary數據的代碼中提到的底部SQL Server的圖片。所以我想檢索圖片到一個控制asp.net的Image;請指導我。圖像到asp.net圖像控制

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"; 
    } 

回答

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; 

不過,我會說這是不是做的最好的方法,您應在上傳的圖片的文件保存在您的網站和保存文件的路徑在你的數據庫中。

0

yogi的回答原則上是正確的,但需要一個web服務器目錄「temp」,並在IIS目錄上寫入訪問權限。

您也可以使用image handler as explained in another SO question解決問題。數據庫檢索以相同的方式完成,但是呈現來自流,而不是臨時文件。