2

我有一个 FileUploadfileupload2控件和一个图像框控件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
4

1 回答 1

-1

要在图像框中显示图像,您需要提供图像路径或 url。您不能直接从数据库中读取它。

一种方法是

  1. 从数据库中检索图像
  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"
    
于 2012-11-21T08:10:26.903 回答