Update image file in database

Last Reply on Apr 25, 2016 05:01 AM By power

Posted on Apr 18, 2016 01:45 AM

I tried to update existing image using the code shown below. Then when I retrieve the image file, my image button only shows "X" icon. What is wrong with this code.

Dim filePath As String = FileUpload2.PostedFile.FileName
        Dim filename As String = Path.GetFileName(filePath)
        Dim ext As String = Path.GetExtension(filename)
        Dim contenttype As String = String.Empty

        Dim filestr As Stream = FileUpload2.PostedFile.InputStream
        Dim binaryread As BinaryReader = New BinaryReader(filestr)
        Dim byt As Byte() = binaryread.ReadBytes(CType(filestr.Length, Int32))

Dim con_1 As String = ConfigurationManager.ConnectionStrings("TestConnectionString").ConnectionString
                Dim Connect As New SqlConnection(con_1)
                Dim Co As New SqlCommand("SELECT * FROM T_PhotoAlbum WHERE Username LIKE @User_Name", Connect)
                Co.Parameters.AddWithValue("@User_Name", lblLogIn_Username.Text & "%")

                Connect.Open()
                'The following "Try Catch" statement INSERTS the name of the Username into T_PhotoAlbum. 
                Try
                    'The UPDATE Syntax is the correct way to add values when updateing a colomun is required.
                    Dim sql As String = "UPDATE T_PhotoAlbum SET Name2=@Name2, ContentType2=@ContentType2, Photo2=@Photo2 WHERE Username=@Username"
                    Dim comnd As New SqlCommand(sql, Connect)

                    comnd.Parameters.AddWithValue("@Username", lblLogIn_Username.Text.ToString)
                    comnd.Parameters.AddWithValue("@ContentType2", SqlDbType.VarChar).Value = contenttype
                    comnd.Parameters.AddWithValue("@Name2", SqlDbType.VarChar).Value = filename
                    comnd.Parameters.AddWithValue("@Photo2", SqlDbType.Binary).Value = byt
                    comnd.ExecuteNonQuery()
                    Connect.Close()

                Catch ex As Exception
                    Dim message2 As String = "Error while Updating record. " & ex.Message
                    Dim sb2 As New System.Text.StringBuilder()
                    sb2.Append("<script type = 'text/javascript'>")
                    sb2.Append("window.onload=function(){")
                    sb2.Append("alert('")
                    sb2.Append(message2)
                    sb2.Append("')};")
                    sb2.Append("</script>")
                    ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", sb2.ToString())
                Finally
                    Connect.Close()
                End Try

 

Posted on Apr 25, 2016 05:01 AM

Thank you. I figured there was some issue with the web page itself. I created new page and it works fine.

Thanks