如何使用Asp.Net通过VB.Net在SQL Server 2008R2中保存和检索图像

时间:2012-11-21 07:23:02

标签: asp.net sql-server vb.net

我有一个FileUpload fileupload2控件和一个图像框控件image1。现在我想保存浏览图像,并在浏览路径时将其显示在图像框上。我正在编写如下代码。

该代码中的问题是什么以及当我浏览路径时如何在图像框中显示它?

Protected Sub btnsave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnsave.Click
    Connection()

    Dim cmd As New SqlCommand
    cmd.Connection = cn
    cmd.CommandText = "INSERT INTO Personal_info (image_id,pic)VALUES (@image_id,@pic)"

    cmd.Parameters.Add("@image_id", SqlDbType.VarChar, 200)
    cmd.Parameters.Add("@pic", SqlDbType.Image, 200)

    cmd.Parameters("@image_id").Value = txtid.Text
    cmd.Parameters("@pic").Value = FileUpload2.FileBytes

    Dim i = -1

    i = cmd.ExecuteNonQuery

    If i = -1 Then
        lblMessage.ForeColor = Drawing.Color.Red
        lblMessage.Text = "Fail to Save"
        'MsgBox("Fail", MsgBoxStyle.OkOnly, "Error")
    Else
        lblMessage.ForeColor = Drawing.Color.Green
        lblMessage.Text = "Success to Save"
    End If
End Sub

1 个答案:

答案 0 :(得分:-1)

要在图像框中显示imange,您需要提供imange路径或网址。你无法直接从数据库中读取它。

一种方法是

  1. 从数据库中检索imange
  2. 将图像保存在服务器中
  3. 将图像服务器路径传递给图像框

    '1. retrieve the imange from the database
    Dim cmd As New SqlCommand
    cmd.Connection = cn
    cmd.CommandText = "SELECT pic FROM Personal_info  WHERE image_id=@image_id;"
    
    cmd.Parameters.Add("@image_id", image_id)
    
    Dim rd As SqlDataReader = cmd.ExecuteReader
    Dim MyData() As Byte
    If rd.Read Then
        If rd("pic").ToString <> Nothing Then
            MyData = rd("pic")
        End If
    
    End If
    
    '2. save the image in the server
    Dim oFileStream As New System.IO.FileStream(System.AppDomain.CurrentDomain.BaseDirectory & "image\image.jpg", System.IO.FileMode.Create, IO.FileAccess.ReadWrite)
    oFileStream.Write(MyData, 0, MyData.Length)
    oFileStream.Close()
    
    '3. pass the image box the image server path
    image1.ImageUrl = "~/image/image.jpg"