First we have taken a sql database table (items) with a image type field in it.Next we have to create a connection using a module..
The module should look like this
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient
Public Module connection
Public con As New SqlConnection("Data Source=.\SQLEXPRESS;_AttachDbFilename='J:\shopping\App_Data\Database.mdf';Integrated_ Security=True;User Instance=True")
Public com As New SqlCommand
Public dr As SqlDataReader
End Module
Now to add the image follow the following steps :
Try
Dim imgByte As Byte() = Nothing
If FileUpload1.PostedFile IsNot Nothing AndAlso FileUpload1.PostedFile.FileName <> "" Then
Dim File As HttpPostedFile = FileUpload1.PostedFile
imgByte = New Byte(File.ContentLength - 1) {}
File.InputStream.Read(imgByte, 0, File.ContentLength)
End If
Dim b As Boolean
con.Open()
com.CommandText = "insert into items values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox7.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "',@eimg)"
com.Parameters.AddWithValue("@eimg", imgByte)
com.Connection = con
com.ExecuteNonQuery()
MsgBox("inserted")
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
com.Cancel()
com.Parameters.Clear()
dr.Close()
End Try
First we shall upload the file using a fileupload control then we shall convert it into a byte stream and would store it into a byte array.Next we would store this byte array into the items database using parametarised query.Hence the image gets stored into the image field
No comments:
Post a Comment