| 介绍 可能有很多的时候,我们急需把图片存入到数据库当中。在一些应用程序中,我们可能有一些敏感的资料,由于存储在文件系统(file system)中的东西,将很容易被某些用户盗取,所以这些数据不能存放在文件系统中。 在这篇文章中,我们将讨论怎样把图片存入到sql2000当中。 在这篇文章中我们可以学到以下几个方面的知识: 1. 插入图片的必要条件 2. 使用流对象 3. 查找准备上传的图片的大小和类型 4.怎么使用inputstream方法? 插入图片的必要条件 在我们开始上传之前,有两件重要的事我们需要做: #form 标记的 enctype 属性应该设置成 enctype="multipart/form-data" # 需要一个表单来使用户选择他们要上传的文件,同时我们需要导入 system.io名称空间来处理流对象 把以上三点应用到aspx页面。同时我们需要对sqlserver做以下的准备。 # 需要至少含有一个图片类型的字段的表 # 如果我们还有另外一个变字符类型的字段来存储图片类型,那样会更好一些。 现在,我们准备了一个sql表(包含了一个image数据类型的字段),还有标记。当然我们还得准备submit按钮,以便用户在选择了图片以后提交。在这个按钮的onclick事件里,我们需要读取选取图片的内容,然后把它存入到表里。那我们先来看看这个onclick事件。 提交按钮的onclick事件的代码: dim intimagesize as int64 dim strimagetype as string dim imagestream as stream ' gets the size of the image intimagesize = personimage.postedfile.contentlength ' gets the image type strimagetype = personimage.postedfile.contenttype ' reads the image imagestream = personimage.postedfile.inputstream dim imagecontent(intimagesize) as byte dim intstatus as integer intstatus = imagestream.read(imagecontent, 0, intimagesize) ' create instance of connection and command object dim myconnection as new sqlconnection(configurationsettings.appsettings("connectionstring")) dim mycommand as new sqlcommand("sp_person_isp", myconnection) ' mark the command as a sproc mycommand.commandtype = commandtype.storedprocedure ' add parameters to sproc dim prmpersonimage as new sqlparameter("@personimage", sqldbtype.image) prmpersonimage.value = imagecontent mycommand.parameters.add(prmpersonimage) dim prmpersonimagetype as new sqlparameter("@personimagetype", sqldbtype.varchar, 255) prmpersonimagetype.value = strimagetype mycommand.parameters.add(prmpersonimagetype) try myconnection.open() mycommand.executenonquery() myconnection.close() response.write("new person successfully added!") catch sqlexc as sqlexception response.write("insert failed. error details are: " & sqlexc.tostring()) end try 这是怎么工作的呢? personimage是htmlinputfile控件的对象。首先需要获得图片的大小,可以使用下面的代码实现: intimagesize = personimage.postedfile.contentlength 然后返回图片的类型使用contentype属性。最后,也是最重要的事就是取得image stream,这可以用以下代码实现: imagestream = personimage.postedfile.inputstream 我们需要一个字节型数组来存储image 内容。读取整个图片可以使用stream对象的read方法来实现。read(in byte[] buffer,int offset,int count)方法有三个参数。【关于read方法的详细可以参看.net frameworksdk】他们是: buffer 字节数组。此方法返回时,该缓冲区包含指定的字符数组,该数组的 offset 和 (offset + count) 之间的值由从当前源中读取的字节替换。 offset buffer 中的从零开始的字节偏移量,从此处开始存储从当前流中读取的数据。 count 要从当前流中最多读取的字节数。 这个read方法用以下代码实现: intstatus = imagestream.read(imagecontent, 0, intimagesize) . 现在,我们已经读取了整个图片的内容,下一步,我们要把这些内容存入到sql 表。我们将使用存储过程来完成插入图片类型和图片内容到sql 表。如果你浏览了上面的代码,你将会发现我们使用了sqldbtype.image的数据类型(datatype)。ok了,完成了这些,我们也就成功的把图片存入到sqlserver中了。下面是我们编写的aspx页面。 结论 我们已经讨论了如何把图片存入到sql server,那么我们如何从sqlserver中读取图片呢?可以参看另一篇文章:在asp.net中从sqlserver中检索图片。
| |||