当前位置:首页 > 网络编程 > WEB编程 > ASP.net >  在ASP.net中保存/取出图片入/从SQL数据库(可用于上传图片)

 在ASP.net中保存/取出图片入/从SQL数据库(可用于上传图片)

点击次数:33 次 发布日期:2008-11-26 12:50:26 作者:源代码网
源代码网推荐      一、把图片存入数据库中
源代码网推荐  
源代码网推荐  用到以下几个方面的知识:
源代码网推荐  1. 使用流对象
源代码网推荐  2. 查找准备上传的图片的大小和类型
源代码网推荐  3.怎么使用InputStream方法
源代码网推荐  
源代码网推荐  插入图片的必要条件
源代码网推荐  1.#Form 标记的 enctype 属性应该设置成 enctype="multipart/form-data"
源代码网推荐  2.# 需要一个<input type=file>表单来使用户选择他们要上传的文件,同时我们需要导入 System.IO名称空间来处理流对象
源代码网推荐  对SqlServer做以下的准备
源代码网推荐  1.# 需要至少含有一个图片类型的字段的表
源代码网推荐  2.# 如果我们还有另外一个变字符类型的字段来存储图片类型,那样会更好一些。
源代码网推荐  
源代码网推荐  窗体控件
源代码网推荐  1.插入图片用到的是System.Web.UI.HtmlControls.HtmlInputFile控件,我们在webform中放入这个控件,取名为“imgInput”
源代码网推荐  2.同时再放入一个确认上传按钮“Button1”
源代码网推荐  
源代码网推荐  程序代码
源代码网推荐  AddImg,用于返回要上传的图片内容
源代码网推荐  
源代码网推荐   1Private Function AddImg()Function AddImg(ByVal InputImg As System.Web.UI.HtmlControls.HtmlInputFile, ByVal ImgType As String, ByVal MaxSize As Int64) As Byte()
源代码网推荐   2"传入一个htmlinputfile控件,一个上传图片格式和一个上传图片最大值,返回图片的内容,既要写入数据库中的内容,你也可以同时写入图片类型
源代码网推荐   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("图片类型为""")</script>") "jgp类型为"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("图片不得大于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
源代码网推荐  示例调用
源代码网推荐  
源代码网推荐  Dim imageContent() As Byte
源代码网推荐   imageContent = AddImg(fileImg, "image/pjpeg", 512000)"上传图片类型为jpg,最大不超过500K
源代码网推荐  
源代码网推荐  插入数据库
源代码网推荐  
源代码网推荐  我想这部分就不用写了吧,你可以用任何方式(推荐使用存储过程),将imageContent插入到数据库中类型为image的字段就行了。
源代码网推荐  
源代码网推荐  二、把图片从数据库中读出
源代码网推荐  
源代码网推荐  这部分比较简单:
源代码网推荐  
源代码网推荐  假设img变量是你从数据库中取出的图片内容
源代码网推荐  那么直接使用
源代码网推荐  Response.BinaryWrite(img)
源代码网推荐  就可以将图片输出到页面上了
源代码网推荐  
源代码网推荐  三:总结
源代码网推荐  
源代码网推荐  将图片存放在数据库中其实是起到了图片保护的作用,这样就算别人浏览你的机器也看不到你的图片,也可以用来保护重要的图片资料。
源代码网推荐  
源代码网推荐  
源代码网推荐    做人要厚道,请注明转自酷网动力(www.ASPCOOL.COM)。
源代码网推荐


源代码网供稿.
网友评论 (0)
会员中心
网络编程
本站推荐
网络编程之精华