You must properly set up the SQL Server database table to accept images, as well as provide
a way on your Web Form to upload an image and send it to the SQL Server.
The table that will store the image must utilize the
image data type on a column that
will store the image. In the following examples, the name of this column is called Image.
In the .ASPX file:
<form enctype="multipart/form-data" runat="server">
<input id="ImageFile" runat="server" type="file" /><p />
<asp:button runat="server" id="UploadButton" OnClick="UploadImage" />
</form>
In <script runat="server" /> block or codebehind:
Sub UploadImage(sender As Object, e As EventArgs)
Dim connectionString As String = "Enter your Connection String"
Dim imageStream As Stream = ImageFile.PostedFile.InputStream
Dim byteData(ImageFile.PostedFile.ContentLength) As Byte
Dim objConn As New SqlClient.SqlConnection(ConnectionString)
Dim cmdText As String = "INSERT INTO sql_images(Image) VALUES(@image)"
Dim objCommand As New SqlClient.SqlCommand(cmdText, objConn)
Dim objParam As New SqlClient.SqlParameter("@image", SqlDbType.Image)
imageStream.Read(byteData, 0, imageFile.PostedFile.ContentLength)
objParam.Value = byteData
objCommand.Parameters.Add(objParam)
Try
objConn.Open()
objCommand.ExecuteNonQuery()
Catch exc as System.Exception
ErrorLabel.Text = exc.ToString()
Finally
objConn.Close()
imageStream.Close()
End Try
End Sub
Note that you must include the System.Data namespace for this code to compile.
Comments
The <form> tag has an additional attribute called enctype.This attribute allows binary
data to be passed through the form (which is needed for the image).
In the code, the submitted image file is broken into a byte array (imgdata) and then
used as the value of the SqlParameter that is passed in as the image (imgparam, @image).
No comments:
Post a Comment