Wednesday, May 13, 2009

Upload the image and store it in SQL Server


In the HTML Design
Put the Upload control when and some requred text box for your need to store the required value in the database. Here i have the one text box with name TextBox1 for the name of the image, and i get the max value of the id from the database and increment it by one and pass it as a parameter to the currently inserting value.




VB code for upload the image in SQL

Dim conn As New SqlConnection("server=servername;database=databasename;Trusted_Connection=yes")
Dim Cmd As SqlCommand
stream = FileUpload1.PostedFile.InputStream
Dim uploadedFile(stream.Length) As Byte
namePosition = FileUpload1.PostedFile.FileName.LastIndexOf("\") + 1
fileName = FileUpload1.PostedFile.FileName.Substring(namePosition)
fileType = FileUpload1.PostedFile.ContentType
conn.Open()

//To get the max value of the mytable1
Dim cmd1 As New SqlCommand("select max(id) from Table1", conn)
Dim drd As SqlDataReader = cmd1.ExecuteReader()
Dim strint As String
While drd.Read()
strint = drd(0).ToString
End While
Dim intId As Integer = CType(strint, Integer)
intId = intId + 1
drd.Close()

// Insert the the Image in sql database with image type
Dim command As SqlCommand = New SqlCommand("INSERT INTO mytable1(id,pname,productimage,type1) Values(@id1,@PName1,@PImage1,@imagetype)", conn)
command.Parameters.Add("@id1", SqlDbType.Int, 18).Value = intId
command.Parameters.Add _
("@PName1", _
SqlDbType.NVarChar, 10).Value = TextBox1.Text
command.Parameters.Add _
("@ProductImage1", _
SqlDbType.Image, uploadedFile.Length).Value = uploadedFile
command.Parameters.Add("@imagetype", SqlDbType.NVarChar, 20).Value() = FileUpload1.PostedFile.ContentType
command.ExecuteNonQuery()
conn.Close()
Button1.Text = "Sucessfull"




No comments:

Post a Comment