在sql server中保存和输出图片
cashcho(翻译)
关键字 sql server images
出处 http://www.bipinjoshi.com/
介绍
有时候我们需要保存一些binary data进数据库。sql server提供一个叫做image的特殊数据类型供我们保存binary data。binary data可以是图片、文档等。在这篇文章中我们将看到如何在sql server中保存和输出图片。
建表
为了试验这个例子你需要一个含有数据的table(你可以在现在的库中创建它,也可以创建一个新的数据库),下面是它的结构:
| column name | datatype | purpose |
| id | integer | identity column primary key |
| imgtitle | varchar(50) | stores some user friendly title to identity the image |
| imgtype | varchar(50) | stores image content type. this will be same as recognized content types of asp.net |
imgdata | image | stores actual image or binary data. |
stream imgdatastream = file1.postedfile.inputstream; int imgdatalen = file1.postedfile.contentlength; string imgtype = file1.postedfile.contenttype; string imgtitle = textbox1.text; byte[] imgdata = new byte[imgdatalen]; int n = imgdatastream.read(imgdata,0,imgdatalen); string connstr= ((namevaluecollection)context.getconfig ("appsettings"))["connstr"]; sqlconnection connection = new sqlconnection(connstr); sqlcommand command = new sqlcommand ("insert into imagestore(imgtitle,imgtype,imgdata) values ( @imgtitle, @imgtype,@imgdata )", connection ); sqlparameter paramtitle = new sqlparameter ("@imgtitle", sqldbtype.varchar,50 ); paramtitle.value = imgtitle; command.parameters.add( paramtitle); sqlparameter paramdata = new sqlparameter ( "@imgdata", sqldbtype.image ); paramdata.value = imgdata; command.parameters.add( paramdata ); sqlparameter paramtype = new sqlparameter ( "@imgtype", sqldbtype.varchar,50 ); paramtype.value = imgtype; command.parameters.add( paramtype ); connection.open(); int numrowsaffected = command.executenonquery(); connection.close(); |
private void page_load(object sender, system.eventargs e) { string imgid =request.querystring["imgid"]; string connstr=((namevaluecollection) context.getconfig("appsettings"))["connstr"]; string sql="select imgdata, imgtype from imagestore where id = " + imgid; sqlconnection connection = new sqlconnection(connstr); sqlcommand command = new sqlcommand(sql, connection); connection.open(); sqldatareader dr = command.executereader(); if(dr.read()) { response.contenttype = dr["imgtype"].tostring(); response.binarywrite( (byte[]) dr["imgdata"] ); } connection.close(); } |
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器