对SqlServer做以下的准备
1.# 需要至少含有一个图片类型的字段的表
2.# 如果我们还有另外一个变字符类型的字段来存储图片类型,那样会更好一些。
窗体控件
1.插入图片用到的是System.Web.UI.HTMLControls.HTMLInputFile控件,我们在webform中放入这个控件,取名为“imgInput”
2.同时再放入一个确认上传按钮“Button1”
程序代码
AddImg,用于返回要上传的图片内容

Private Function AddImg()Function AddImg(ByVal InputImg As System.Web.UI.HTMLControls.HTMLInputFile, ByVal ImgType As String, ByVal MaxSize As Int64) As Byte()
"传入一个HTMLinputfile控件,一个上传图片格式和一个上传图片最大值,返回图片的内容,既要写入数据库中的内容,你也可以同时写入图片类型
Dim intImageSize As Int64
Dim strImageType As String
Dim ImageStream As Stream
" Gets the Image Type
strImageType=InputImg.PostedFile.ContentType
If strImageType <> ImgType Then
Response.Write("<script>alert("图片类型为""")</script>") "jgp类型为"image/pjpeg"
Exit Function
End If
" Gets the Size of the Image
intImageSize = InputImg.PostedFile.ContentLength
If intImageSize > MaxSize Then
Response.Write("<script>alert("图片不得大于K")</script>")
Exit Function
End If
" Reads the Image
ImageStream = InputImg.PostedFile.InputStream
Dim ImageContent(intImageSize) As Byte
Dim intStatus As Integer
intStatus = ImageStream.Read(ImageContent, 0, intImageSize)
Return ImageContent
End Function示例调用
Dim imageContent() As Byte
imageContent = AddImg(fileImg, "image/pjpeg", 512000)"上传图片类型为jpg,最大不超过500K
插入数据库
我想这部分就不用写了吧,你可以用任何方式(推荐使用存储过程),将imageContent插入到数据库中类型为image的字段就行了。
二、把图片从数据库中读出
这部分比较简单:
假设img变量是你从数据库中取出的图片内容
那么直接使用
Response.BinaryWrite(img)
就可以将图片输出到页面上了
三:总结
将图片存放在数据库中其实是起到了图片保护的作用,这样就算别人浏览你的机器也看不到你的图片,也可以用来保护重要的图片资料