First drag and drop FileUpload and button control in .aspx page.
<asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
We insert image when button is submit.code for on button click,
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click Dim imgSize As Int64 Dim imgType As String Dim imgStream As Stream
'Get the Size of the Image imgSize = FileUpload1.PostedFile.ContentLength
'Get type of Image imgType = FileUpload1.PostedFile.ContentType
'Get image Stream imgStream = FileUpload1.PostedFile.InputStream '1 dimensional array of byte Dim ImageContent(imgSize) As Byte 'Read Image stream imgStream.Read(ImageContent, 0, imgSize)
'Insert image name,image type and image in database. con = New SqlConnection(ConfigurationManager.ConnectionStrings("conString").ConnectionString) cmd = New SqlCommand()
cmd.Connection = con cmd.CommandType = CommandType.Text cmd.CommandText = "INSERT INTO [tblImage] ([imgName],[imgType],[image]) VALUES (@imgName,@imgType,@image)"
cmd.Parameters.Add("@imgName", SqlDbType.VarChar).Value = FileUpload1.FileName cmd.Parameters.Add("@imgType", SqlDbType.VarChar).Value = imgType cmd.Parameters.Add("@image", SqlDbType.Image).Value = ImageContent
Try con.Open() cmd.ExecuteNonQuery() con.Close()
Catch ex As SqlException Response.Write("Error: " & ex.ToString) End Try End Sub
In above code first we find the size of image,type of image and image stream.Then,create 1-dimensional byte array as size of image(imgSize).Then,read the image stream,imgStream.Read(ImageContent, 0, imgSize).
This Read method has three argument Read(buffer() as byte,offset as Integer,count as Integer) buffer() where we copy Image content. Offset staring postion to read. count number of bytes to be read.
And then insert image name,image type and image in database.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|