2010-03-09 61 views
1

对于专业人员来说,这应该非常简单。我在sql server数据库中有图像,我想在我的aspx(vb.net)文件中检索它们。 我在ASPX这个图像控制 - 在vb.net我已经开始这个代码 -从vb.net的sql数据库显示/检索图像

Private Sub ImageDisplay() 
    Dim SqlCnn As SqlConnection = Nothing, sql As String = "" 
    ConnectDB(SqlCnn) 
    Try 
     sql = "SELECT image FROM employees (NOLOCK) WHERE ID =" & emp_id 
     sqlcmd = New SqlCommand(sqlstr, SqlCnn) 
     Dim imageData As Byte() = DirectCast(sqlcmd.ExecuteScalar(), Byte()) 
     Dim newImage As Image = Nothing 
     If Not imageData Is Nothing Then 
      Using ms As New MemoryStream(imageData, 0, imageData.Length) 
       ms.Write(imageData, 0, imageData.Length) 
       newImage = Image.FromStream(ms, True) 
      End Using 
      image1.Image = newImage 
     End If 
    Catch ex As Exception 
     ReportError(ex) 
    Finally 
     CloseDB(SqlCnn) 
    End Try 
End Sub 

我在2个地方收到错误。 - newImage = Image.FromStream(ms,True) - image1.Image = newImage Fromstream不是system.web.ui.webcontrols.image的成员 和第二个错误图像不是system.web.ui的成员.webcontrols.image

+0

没有人?? cmon它不能那么难! – ferdd

+0

你必须有点耐心。人们会在他们碰巧看到你的问题时回答,他们不会坐在24-7等待它。 – Guffa

+0

哈哈np。 anywyas我正在尝试这个代码,但在某个地方出错了。让我编辑这个问题。 – ferdd

回答

2

您需要一个命令对象和一个数据读取器。但是,你把它们放在错误的页面中。

如果您查看Image控件的属性,您将会看到它没有任何Image属性,因此无法加载图像并将其放入控件中。原因是您无法以相同的响应发送页面和图像,而是浏览器在页面加载时必须单独请求图像。

要从数据库获取图像并显示在网页中,您需要一个单独的代理页面,您可以使用它来从数据库中仅获取图像数据。在Image控件的ImageUrl属性中,您将放置类似"GetImage.ashx"的东西。然后你创建一个具有该名称的HTTP处理程序,它只会从数据库获取图像数据并写入响应流。

实施例:

Private Sub HandleRequest(context as HttpContext) 
    Dim SqlCnn As SqlConnection = Nothing, sql As String 
    Dim emp_id As Integer 
    emp_id = Int32.Parse(context.Request.QueryString("id")) 
    ConnectDB(SqlCnn) 
    Try 
    sql = "SELECT image FROM employees (NOLOCK) WHERE ID =" & emp_id 
    sqlcmd = New SqlCommand(sqlstr, SqlCnn) 
    Dim imageData As Byte() = DirectCast(sqlcmd.ExecuteScalar(), Byte()) 
    context.Response.ContentType = "image/jpeg" 
    context.Response.BinaryWrite(imageData) 
    Catch ex As Exception 
    ReportError(ex) 
    Finally 
    CloseDB(SqlCnn) 
    End Try 
End Sub 
+0

你有这样的例子吗?代码明智。因为我理解这个概念,但不知道如何编写代码 – ferdd

+0

@ferdd:我在上面添加了一个例子。 – Guffa