1. Store the image in the database
Use the following knowledge:
1. Use stream objects
2. Find the size and type of image to upload
3. How to use the InputStream method
to insert the necessary conditions for pictures
1. The enctype attribute of the #Form tag should be set to enctype="multipart/form-data"
2.# We need an <input type=file> form to allow users to select the files they want to upload. At the same time, we need to import the System.IO namespace to process the stream object and make the following preparations for SqlServer.
1.# Requires a table containing at least one image type field
2.# It would be better if we have another variable character type field to store the image type.
form control
1. The System.Web.UI.HtmlControls.HtmlInputFile control is used to insert pictures. We put this control in the webform and name it "imgInput"
2. At the same time, add a confirmation upload button "Button1"
program code
AddImg, used to return the image content to be uploaded
1Private Function AddImg()Function AddImg(ByVal InputImg As System.Web.UI.HtmlControls.HtmlInputFile, ByVal ImgType As String, ByVal MaxSize As Int64) As Byte()
2' Pass in an htmlinputfile control, an uploaded image format and an uploaded image maximum value, and return the content of the image. You need to write the content in the database, and you can also write the image type at the same time.
3 Dim intImageSize As Int64
4 Dim strImageType As String
5 Dim ImageStream As Stream
6 ' Gets the Image Type
7 strImageType=InputImg.PostedFile.ContentType
8 If strImageType <> ImgType Then
9 Response.Write("<script>alert('The picture type is ""')</script>") 'The jgp type is "image/pjpeg"
10 Exit Function
11 End If
12 ' Gets the Size of the Image
13 intImageSize = InputImg.PostedFile.ContentLength
14 If intImageSize > MaxSize Then
15 Response.Write("<script>alert('Picture must not be larger than K')</script>")
16 Exit Function
17 End If
18 ' Reads the Image
19 ImageStream = InputImg.PostedFile.InputStream
20 Dim ImageContent(intImageSize) As Byte
21 Dim intStatus As Integer
22 intStatus = ImageStream.Read(ImageContent, 0, intImageSize)
23 Return ImageContent
24 End Function
Example call
Dim imageContent() As Byte
imageContent = AddImg(fileImg, "image/pjpeg", 512000)'The uploaded image type is jpg, and the maximum size cannot exceed 500K.
Insert it into the database.
I don’t think you need to write this part. You can use any method (stored procedures are recommended). Just insert imageContent into a field of type image in the database.
2. Reading the image from the database
is relatively simple:
assuming the img variable is the image content you retrieved from the database, then use it directly
Response.BinaryWrite(img)
You can output the picture to the page.
Three: Summary:
Storing pictures in the database actually plays a role in picture protection. This way, even if others browse your machine, they cannot see your pictures. It can also be used to protect important pictures. material.