怎样将图片上传到数据库进行保存

合集下载

如何将图片插入到数据库中

如何将图片插入到数据库中

试验十数据库编程‎1、新建项目项目名称为‎“d bgl”。

2、设计如下窗‎体:窗体上放置‎的控件有:7个按钮,一个gro‎upBox‎,4个lab‎el,4个tex‎tBox,1个pic‎tureB‎o x和1个‎d ataG‎r idVi‎e w。

3、编写连接数‎据库的类鼠标单击菜‎单栏上的“项目”选择“项目”菜单中的“添加类”命令,为“dbgl”项目添加连‎接数据库的‎类,类名是:DbCon‎n ecti‎o n。

如下图所示‎:DbCon‎n ecti‎o n类的代‎码如下图所‎示:注意需要引‎入Sy st‎e m.Data.SqlCl‎i ent名‎称空间。

4、编写操作数‎据的类为“dbgl”项目添加操‎作数据的类‎,该类名为“DbOpe‎r atio‎n”。

首先,实例化“DbCon‎n ecti‎o n”类,代码如下:其次,编写方法g‎e tdat‎a set,该方法返回‎一个Dat‎aSet对‎象的数据集‎。

代码如下:接着编写执‎行SQL语‎句的方法“sqlcm‎d”。

该方法的代‎码如下:最后编写方‎法“GetTa‎b le”,该方法用于‎返回一个D‎a taTa‎b le类型‎的数据。

代码如下:5、为窗体编写‎代码,完成对数据‎库操作的功‎能。

在窗体的代‎码视图中:(1)定义一个窗‎体级别的B‎i ndin‎g Mana‎g erBa‎s e类变量‎m ybin‎d用来管理‎多个控件绑‎定到一个数‎据源,以便实现同‎步操作。

代码如下:(2)在窗体的L‎o ad事件‎中编写,为相关控件‎绑定相数据‎。

代码如下:(3)为“第一条”按钮控件编‎写代码:代码如下图‎所示:(4)为“下一条”按钮控件编‎写代码:代码如下图‎所示:(5)为“上一条”按钮控件编‎写代码:代码如下图‎所示:(6)为“最后一条”按钮控件编‎写代码:代码(略)。

自己编写(7)给“新增”按钮编写代‎码,完成添加一‎条记录首先,给项目添加‎一个窗体,窗体名称为‎“FormB‎a se”。

Express实现前端后端通信上传图片之存储数据库(mysql)傻瓜式教程(一)

Express实现前端后端通信上传图片之存储数据库(mysql)傻瓜式教程(一)

Express实现前端后端通信上传图⽚之存储数据库(mysql)傻⽠式教程(⼀)在前端这个坑⾥摸爬滚打已经⼀年多了,终于下定决⼼写下⾃⼰第⼀篇博客(虽然内容原创居少,算是个整合内容),开始使⽤express的原因是因为⾃⼰想测试接收下前端上传图⽚并返回,实现图⽚上传。

后端各位⼤⼤们⼜都⽐较忙,没办法了,只能⾃⼰上了(哎,都是逼出来的)。

此教程适合没有接触过node的web前端开发,快速构建⾃⼰的框架,基于express4.x。

安装完成后,继续安装express的应⽤⾻架,⽣成默认项⽬$ npm install express-generator -g (-g表⽰全局安装,下次可以直接使⽤,不⽤再次安装) 接着在myapp⽂件夹下直接运⾏express,项⽬⽬录就直接⽣成了  然后安装所有依赖包:$ npm install 启动这个应⽤(MacOS 或 Linux 平台):$ DEBUG=myapp npm start Windows 平台使⽤如下命令:> set DEBUG=myapp & npm start 看到这个页⾯时,⼤家已经完成了基础的项⽬构建,继续往上添加⾃⼰的代码就可以了。

(到这部后⼤家可以把public ⽬录下的⽂件夹修改为⾃⼰喜欢的格式,例如:js,css,只是⼀个路径⽽已) 现在⼤家打开核⼼的app.js 下⾯咱们先不急着上传图⽚,先测试下前端发送的post和get请求。

以post请求为例,咱们把layout.jade修改成下⾯的样⼦doctype htmlhtmlheadtitle= titlelink(rel='stylesheet', href='/css/style.css')script(type="text/javascript", src="/js/jquery.js")script(type="text/javascript", src="/js/index.js")bodyblock content 在public/js下新建个index.js,加载jquery(只是为了简写的ajax)有⼈可能会问为什么会没有public路径,因为Express 内置的 express.static 可以⽅便地托管静态⽂件,例如图⽚、CSS、JavaScript ⽂件等,详细内容点这⾥,对应app.js的内容为e(express.static(path.join(__dirname, 'public')));只有这样才能读取到⽂件。

C# 图片保存到数据库和从数据库读取图片并显示

C# 图片保存到数据库和从数据库读取图片并显示

C# 图片保存到数据库和从数据库读取图片并显示图片保存到数据库的方法:public void imgToDB(string sql){ //参数sql中要求保存的imge变量名称为@images//调用方法如:imgToDB("update UserPhoto set Photo=@images where UserNo='" + temp + "'");FileStream fs = File.OpenRead(t_photo.Text);byte[] imageb = new byte[fs.Length];fs.Read(imageb, 0, imageb.Length);fs.Close();SqlCommand com3 = new SqlCommand (sql,con);com3.Parameters.Add("@images", SqlDbType.Image).Value = imageb;if (com3.Connection.State == ConnectionState.Closed)com3.Connection.Open();try{com3.ExecuteNonQuery();}catch{ }finally{ com3.Connection.Close(); }}数据库中读出图片并显示在picturebox中:方法一:private void ShowImage(string sql){//调用方法如:ShowImage("select Photo from UserPhoto where UserNo='" + userno +"'");SqlCommand cmd = new SqlCommand(sql, conn);conn.Open();byte[] b= (byte[])cmd.ExecuteScalar();if (b.Length 〉0){MemoryStream stream = new MemoryStream(b, true);stream.Write(b, 0, b.Length);pictureBox1.Image = new Bitmap(stream);stream.Close();}conn.Close();}方法二:当在dg中选中某行时:private void dg_MouseUp(object sender, MouseEventArgs e){//整行选择if (e.Button == System.Windows.Forms.MouseButtons.Left){//用户编号,姓名,性别,身份证号,籍贯,学院,系所,校区,部门,电话,照片//显示相片object imgobj=dg[10, dg.CurrentRow.Index].Value;if (imgobj != null && !Convert.IsDBNull(imgobj)){byte[] imgb = (byte[])imgobj;MemoryStream memStream = new MemoryStream(imgb);try{Bitmap myimge = new Bitmap(memStream);this.pictureBox1.Image = myimge;}catch{DB.msgbox("从数据库读取相片失败!");}}elsepictureBox1.Image = null;}}。

PHP上传图片到数据库并显示的实例代码

PHP上传图片到数据库并显示的实例代码

PHP上传图⽚到数据库并显⽰的实例代码PHP上传图⽚到数据库并显⽰1、创建数据表CREATE TABLE ccs_image (id int(4) unsigned NOT NULL auto_increment,description varchar(250) default NULL,bin_data longblob,filename varchar(50) default NULL,filesize varchar(50) default NULL,filetype varchar(50) default NULL,PRIMARY KEY (id))engine=myisam DEFAULT charset=utf82、⽤于上传图⽚到服务器的页⾯ upimage.html<!doctype html><html><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><style type="text/css">*{margin: 1%}</style><title>Document</title></head><body><form method="post" action="upimage.php" enctype="multipart/form-data">描述:<input type="text" name="form_description" size="40"><input type="hidden" name="MAX_FILE_SIZE" value="1000000"> <br>上传⽂件到数据库:<input type="file" name="form_data" size="40"><br><input type="submit" name="submit" value="submit"></form></body></html>3、处理图⽚上传的php upimage.php<?phpif (isset($_POST['submit'])) {$form_description = $_POST['form_description'];$form_data_name = $_FILES['form_data']['name'];$form_data_size = $_FILES['form_data']['size'];$form_data_type = $_FILES['form_data']['type'];$form_data = $_FILES['form_data']['tmp_name'];$dsn = 'mysql:dbname=test;host=localhost';$pdo = new PDO($dsn, 'root', 'root');$data = addslashes(fread(fopen($form_data, "r"), filesize($form_data)));//echo "mysqlPicture=".$data;$result = $pdo->query("INSERT INTO ccs_image (description,bin_data,filename,filesize,filetype) VALUES ('$form_description','$data','$form_data_name','$form_data_size','$form_data_type')"); if ($result) {echo "图⽚已存储到数据库";} else {echo "请求失败,请重试";注:图⽚是以⼆进制blob形式存进数据库的,像这样4、显⽰图⽚的php getimage.php<?php$id =2;// $_GET['id']; 为简洁,直接将id写上了,正常应该是通过⽤户填⼊的id获取的$dsn ='mysql:dbname=test;host=localhost';$pdo = new PDO($dsn,'root','root');$query = "select bin_data,filetype from ccs_image where id=2";$result = $pdo->query($query);$result = $result->fetchAll(2);// var_dump($result);$data = $result[0]['bin_data'];$type = $result[0]['filetype'];Header( "Content-type: $type");echo $data;5、到浏览器查看已经上传的图⽚,看是否可以显⽰以上就是本次介绍的全部相关知识点,感谢⼤家的学习和对的⽀持。

ASP上传图片到数据库图片大小有限制的解决方法

ASP上传图片到数据库图片大小有限制的解决方法

ASP上传图片到数据库图片大小有限制的解决方法(“电脑编程技巧与维护”上半月刊)我在日常工作中开发了一个网站,需要将一些图片上传到数据库,采用ASP+ACCESS方法,后台服务操作系统为WIN2003,我的上传代码如下:1、上传图片界面代码<html><head><meta name="VI60_defaultClientScript" content="VBScript"><title> File Upload </title></head><body><form name="form2" ENCTYPE="multipart/form-data" ACTION="SA VE_PIC.asp" METHOD="POST" ><br><br><br><br><table width="71%" cellpadding="0" border="1" cellspacing="0" bordercolor="#0078C8" bordercolorlight="#0078C8" bordercolordark="#FFFFFF" align="center"> <tr> <td colspan="2"><div align="center"><font size="5"><b><font color="#FF0000">在</font><font size="5" color="#FF0000"><b>下面</b></font><font color="#FF0000">添加图片</font></b></font></div> </td> </tr> <tr> <td colspan="2"><div align="center"><input type=file name=mefile>图1</div> </td></tr><tr><td colspan="2" height="27"><div align="center"><font size="5" color="#FF0000"><b>在下面添加图片</b></font></div> </td></tr> <tr> <td><div align="center">图2<input type=file name=mefile2></div> </td><td><div align="center"> 图3<input type=file name=mefile3></div> </td></tr><div align="center"><br><input type="submit" value="提交"><a href="quit.asp"> 安全退出</a></div></form><p>&nbsp;</p></body></html>执行后界面如下:2、SA VE_PIC.asp代码如下:<%Server.ScriptTimeOut =300%><a href="uptext.asp">添加说明</a><%dim mydata(10)response.buffer=true' 图片大小formsize=request.totalbytes'response.write formsize' 读取提交来的数据formdata=request.binaryread(formsize)bncrlf=chrB(13)&chrB(10)' 分隔符divider=leftB(formdata,clng(instrb(formdata,bncrlf))-1) datastart = 0For i=1 To 3' 图片数据开始位置datastart=instrb(datastart+datalen+1, formdata,bncrlf&bncrlf)+4' 图片数据结束位置datalen=instrb(datastart+1,formdata,divider)-datastart' 获取图片数据mydata(i)=midb(formdata,datastart,datalen)Nextdim conndim connstron error resume nextconnstr="DBQ="+server.mappath("pic.mdb")+";DefaultDir=;DRIVER={Microsoft Access Driver (*.mdb)};"set conn=server.createobject("ADODB.CONNECTION")conn.open connstrREM 增加主图片IF LEN(RTRIM(MYDA TA(1))) >2 THENsql="select * from images where imgid is null order by imgid desc"Set rs = Server.CreateObject("ADODB.Recordset")rs.Open sql,conn,3,2rs.addnewrs("img").appendchunk mydata(1) '增加到数据库中rs("bz")="Y"rs.updatesession("sl")=1REM 取得主张图片ID号sql1="select * from images order by imgid desc"Set rs1= Server.CreateObject("ADODB.Recordset")rs1.Open sql1,conn,3,2SESSION("IMGID")=rs1("imgid")ELSEEND IF%><%REM 增加第一张附图片IF LEN(RTRIM(MYDA TA(2))) >2 THENsqlstr = "select * from images where imgid is null order by imgid desc"rs.open sqlstr, conn, 3,2rs.addnewrs("img").appendchunk mydata(2)RS("BZ")="N"rs("newsid")=session("imgid")rs.updatesession("sl")=session("sl")+1ELSEEND IFREM 增加第二张附图片IF LEN(RTRIM(MYDA TA(3))) >2 THENsqlstr = "select * from images where imgid is null order by imgid desc"rs.open sqlstr, conn, 3,2rs.addnewrs("img").appendchunk mydata(3)RS("BZ")="N"rs("newsid")=session("imgid")rs.updatesession("sl")=session("sl")+1ELSEEND IFrs.closeRESPONSE.REDIRECT UPTEXT.ASP%>3、IMAGE表结构如下:IMGID 自动编号IMG OLE对象在开发的过程中,我发现上传较小的图片没有问题,但无法上传较大或多个图片,经过查找资料,我发现不是代码的问题,而是WIN2003 IIS服务默认接收的数据大小为200K,该配置存放在C:\WINDOWS\system32\inetsrv\下的metabase.xml文件中,具体解决办法如下:1、进入IIS服务管理器,在“本地计算机”单击右键,选择“属性”,如图:选中“允许直接编辑配置数据库”,确定后退出。

将图片储存在MySQL数据库中的几种方法

将图片储存在MySQL数据库中的几种方法

将图⽚储存在MySQL数据库中的⼏种⽅法通常对⽤户上传的图⽚需要保存到数据库中。

解决⽅法⼀般有两种:1、将图⽚保存的路径存储到数据库;2、将图⽚以⼆进制数据流的形式直接写⼊数据库字段中。

以下为具体⽅法:⼀、保存图⽚的上传路径到数据库: string uppath="";//⽤于保存图⽚上传路径 //获取上传图⽚的⽂件名 string fileFullname = this.FileUpload1.FileName; //获取图⽚上传的时间,以时间作为图⽚的名字可以防⽌图⽚重名 string dataName = DateTime.Now.ToString("yyyyMMddhhmmss"); //获取图⽚的⽂件名(不含扩展名) string fileName = fileFullname.Substring(stIndexOf("\\") + 1); //获取图⽚扩展名 string type = fileFullname.Substring(stIndexOf(".") + 1); //判断是否为要求的格式 if (type == "bmp" || type == "jpg" || type == "jpeg" || type == "gif" || type == "JPG" || type == "JPEG" || type == "BMP" || type == "GIF") { //将图⽚上传到指定路径的⽂件夹 this.FileUpload1.SaveAs(Server.MapPath("~/upload") + "\\" + dataName + "." + type); //将路径保存到变量,将该变量的值保存到数据库相应字段即可 uppath = "~/upload/" + dataName + "." + type; }⼆、将图⽚以⼆进制数据流直接保存到数据库:引⽤如下命名空间:using System.Drawing; using System.IO; using System.Data.SqlClient; 设计数据库时,表中相应的字段类型为iamge 保存: //图⽚路径 string strPath = this.FileUpload1.PostedFile.FileName.ToString (); //读取图⽚ FileStream fs = new System.IO.FileStream(strPath, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); byte[] photo = br.ReadBytes((int)fs.Length); br.Close(); fs.Close(); //存⼊ SqlConnection myConn = new SqlConnection("Data Source=.;Initial Catalog=stumanage;User ID=sa;Password=123"); string strComm = " INSERT INTO stuInfo(stuid,stuimage) VALUES(107,@photoBinary )";//操作数据库语句根据需要修改 SqlCommand myComm = new SqlCommand(strComm, myConn); myComm.Parameters.Add("@photoBinary", SqlDbType.Binary, photo.Length); myComm.Parameters["@photoBinary"].Value = photo; myConn.Open(); if (myComm.ExecuteNonQuery() > 0) { bel1.Text = "ok"; } myConn.Close(); 读取: ...连接数据库字符串省略 mycon.Open(); SqlCommand command = new SqlCommand("select stuimage from stuInfo where stuid=107", mycon);//查询语句根据需要修改 byte[] image = (byte[])command.ExecuteScalar (); //指定从数据库读取出来的图⽚的保存路径及名字 string strPath = "~/Upload/zhangsan.JPG"; string strPhotoPath = Server.MapPath(strPath); //按上⾯的路径与名字保存图⽚⽂件 BinaryWriter bw = new BinaryWriter(File.Open(strPhotoPath,FileMode.OpenOrCreate)); bw.Write(image); bw.Close(); //显⽰图⽚ this.Image1.ImageUrl = strPath; //采⽤这两种⽅式可以根据实际需求灵活选择。

SQLServer数据库中如何存储图片--教程

SQLServer数据库中如何存储图片--教程

图片文件在SQL Server数据库的存取在很多时候,我们需要将图片文件存入到SQL Server数据库中,并且在使用的时候将数据库中的图片取出。

本文将描述用C#语言来实现这一过程。

数据库表结构如果要将图片数据存入SQL Server数据库的表中,我们必须使用SQL Server的image 数据类型,在被试验中,我们将使用如下的语句创建数据库表StudentInfo:CREATE TABLE [dbo].[StudentInfo]([ID] [int] IDENTITY(1,1)NOT NULL,[Name] [varchar](50)COLLATE Chinese_PRC_CI_AS NULL,[Age] [int] NULL,[Sex] [nchar](10)COLLATE Chinese_PRC_CI_AS NULL,[Class] [varchar](15)COLLATE Chinese_PRC_CI_AS NULL,[Hobby] [varchar](50)COLLATE Chinese_PRC_CI_AS NULL,[Picture] [image] NULL)其中字段Picture字段为image数据类型,用来保存学生的照片。

图片存入数据库要将图片数据存入到数据库表的image数据类型的字段中,首先需要将图片文件中的数据读入到内存字节中,在将内存字节存入数据库中,具体示例代码如下:private void btnUpload_Click(object sender, EventArgs e){//上传图片到数据库OpenFileDialog openDlg = new OpenFileDialog();openDlg.Filter = "图片文件(*.jpg)|*.jpg";string filePath = "";if (openDlg.ShowDialog() == DialogResult.OK){filePath = openDlg.FileName;this.txtFilePath.Text = filePath;this.picShow.ImageLocation = filePath;//打开文件流,用来读取图片文件中的数据FileStream stream = new FileStream(filePath,FileMode.Open,FileAccess.Read);//将文件流中的数据存入内存字节组中byte[] buffer = new byte[stream.Length];stream.Read(buffer,0,(int)stream.Length);stream.Close();try{//调用存储图片数据的存取过程string strName = Path.GetFileName(filePath);string connString = "Data Source=.;Initial Catalog=StuDB;Persist SecurityInfo=True";SqlConnection conn = new SqlConnection(connString);conn.Open();SqlCommand cmd = new SqlCommand("proc_UploadPicture", conn);mandType = CommandType.StoredProcedure;cmd.Parameters.Add("@ID", SqlDbType.Int).Value = 1;cmd.Parameters.Add("@Picture", SqlDbType.Image).Value = buffer;cmd.Parameters.Add("@Ext", SqlDbType.VarChar).Value = strName;cmd.ExecuteNonQuery();conn.Close();}catch (Exception ex){MessageBox.Show(ex.Message);}}}存储过程proc_UploadPicture代码如下:Create procedure [dbo].[proc_UploadPicture]@ID int,@Picture imageASupdate StudentInfo set Picture = @Picturewhere ID = @ID从数据库读取图片要从数据库中获取图片数据,并将图片显示在界面上,需要将数据库中的图片数据读入到内存中,在将内存的数据用位图来格式化,并将位图显示在界面的PictureBox控件中。

图片存入mySql数据库

图片存入mySql数据库

我在程序代码里贴了向Mysql数据库写入image代码的程序,可是好多人都是Java的初学者,对于这段代码,他们无法将它转换成jsp,所以我在这在写一下用jsp怎样向数据库写入图像文件。

大家先在数据库建这样一张表,我下面的这些代码对任何数据库都通用,只要支持blob类型的只要大家将连接数据库的参数改一下就可以了。

SQL>create table image(id int,content varchar(200),image blob);如果在sqlserver2000的数据库中,可以将blob字段换为image类型,这在SqlServer2000中是新增的。

testimage.html文件内容如下:<HTML><HEAD><TITLE>Image File </TITLE><meta http-equiv="Content-Type" content="text/html; charset=gb2312"></HEAD><FORM METHOD=POST ACTION="testimage.jsp"><INPUT TYPE="text" NAME="content"><BR><INPUT TYPE="file" NAME="image"><BR><INPUT TYPE="submit"></FORM><BODY></BODY></HTML>我们在Form的action里定义了一个动作testimage.jsp,它的内容如下:<%@ page contentType="text/html;charset=gb2312"%><%@ page import="java.sql.*" %><%@ page import="java.util.*"%><%@ page import="java.text.*"%><%@ page import="java.io.*"%><html><body><%Class.forName("org.gjt.mm.mysql.Driver").newInstance();Stringurl="jdbc:mysql://localhost/mysql?user=root&password=&useUnicode=true&characterEncoding= 8859_1";//其中mysql为你数据库的名字,user为你连接数据库的用户,password为你连接数据库用户的密码,可自己改Connection conn= DriverManager.getConnection(url);String content=request.getParameter("content");String filename=request.getParameter("image");FileInputStream str=new FileInputStream(filename);String sql="insert into test(id,content,image) values(1,?,?)"; PreparedStatement pstmt=dbconn.conn.prepareStatement(sql);pstmt.setString(1,content);pstmt.setBinaryStream(2,str,str.available());pstmt.execute();out.println("Success,You Have Insert an Image Successfully");%>下面我写一个测试image输出的例子看我们上面程序写的对不对,testimageout.jsp的内容如下:<%@ page contentType="text/html;charset=gb2312"%><%@ page import="java.sql.*" %><%@ page import="java.util.*"%><%@ page import="java.text.*"%><%@ page import="java.io.*"%><html><body><%Class.forName("org.gjt.mm.mysql.Driver").newInstance();Stringurl="jdbc:mysql://localhost/mysql?user=root&password=&useUnicode=true&characterEncoding= 8859_1";//其中mysql为你数据库的名字,user为你连接数据库的用户,password为你连接数据库用户的密码,可自己改Connection conn= DriverManager.getConnection(url);String sql = "select image from test where id=1";Statement stmt=null;ResultSet rs=null;try{stmt=conn.createStatement();rs=stmt.executeQuery(sql);}catch(SQLException e){}try {while(rs.next()) {res.setContentType("image/jpeg");ServletOutputStream sout = response.getOutputStream();InputStream in = rs.getBinaryStream(1);byte b[] = new byte[0x7a120];for(int i = in.read(b); i != -1;){sout.write(b);in.read(b);}sout.flush();sout.close();}}catch(Exception e){System.out.println(e);}%></body></html>你运行这个程序,你就会看到刚才你写入美丽的图片就会显示在你面前。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

这个范例共包括三个ASP文件和一个数据库(一个表),全部在同一目录下。

1、tblImage 表结构(ACCESS 2000)sn 自动编号序列号content-type 文本图片类型image OLE 对象图片数据2、SimpleImageToData.asp:上传表单及保存图片到数据库的代码部分,主要文件。

<%@ Language=VBScript %><% option explicit %><%'从一个完整路径中析出文件名称function getFileNamefromPath(strPath)getFileNamefromPath = mid(strPath,instrrev(strPath,"\")+1)end function'定义数据库连接字符串dim cnstrcnstr = "driver={Microsoft Access Driver (*.mdb)};dbq=" &server.MapPath("./upload.mdb")%><HTML><HEAD><title>单个图像保存到数据库</title><meta http-equiv="Content-Type" content="text/html; charset=gb2312"> </HEAD><body><p><a href="SimpleImageToData.asp">上传图片</a><a href="ShowImageListFromData.asp">显示图片</a><hr></p><%if request.ServerVariables("REQUEST_METHOD") = "POST" thendim sCome, sGo, binData, strDatadim posB, posE, posSB, posSEdim binCrlfdim strPath, strFileName, strContentTypebinCrlf = chrb(13)&chrb(10) '定义一个单字节的回车换行符set sCome = server.CreateObject("adodb.stream")sCome.Type = 1 '指定返回数据类型 adTypeBinary=1,adTypeText=2sCome.Mode = 3 '指定打开模式adModeRead=1,adModeWrite=2,adModeReadWrite=3sCome.OpensCome.Write request.BinaryRead(request.TotalBytes)sCome.Position = 0binData = sCome.Read'response.BinaryWrite binData '调试用:显示提交的所有数据'response.Write "<hr>" '调试用set sGo = server.CreateObject("adodb.stream")sGo.Type = 1sGo.Mode = 3sGo.OpenposB = 1posB = instrb(posB,binData,binCrlf)posE = instrb(posB+1,binData,binCrlf)'response.Write posB & " | " & posE & "<br>"sCome.Position = posB+1sCome.CopyTo sGo,posE-posB-2sGo.Position = 0sGo.Type = 2sGo.Charset = "gb2312"strData = sGo.ReadTextsGo.Close'response.Write strData & "<hr>"posSB = 1posSB = instr(posSB,strData,"filename=""") + len("filename=""")posSE = instr(posSB,strData,"""")if posSE > posSB thenstrPath = mid(strData,posSB,posSE-posSB)'response.Write "本地路径:" & strPath & "<br>"'response.Write "文件名:" & getFileNamefromPath(strPath) & "<br>"posB = posEposE = instrb(posB+1,binData,binCrlf)'response.Write posB & " | " & posE & "<br>"sGo.Type = 1sGo.Mode = 3sGo.OpensCome.Position = posBsCome.CopyTo sGo,posE-posB-1sGo.Position = 0sGo.Type = 2sGo.Charset = "gb2312"strData = sGo.ReadTextsGo.ClosestrContentType = mid(strData,16) '此处因为固定的,所以省略查找 :-) 'response.Write "图片类型:" & strContentType & "<hr>"posB = posE+2posE = instrb(posB+1,binData,binCrlf)'response.Write posB & " | " & posE & "<br>"sGo.Type = 1sGo.Mode = 3sGo.OpensCome.Position = posB+1sCome.CopyTo sGo,posE-posB-2sGo.Position = 0strData = sGo.ReadsGo.Close'response.Write lenb(strData) & "<br>"dim cn, rs, sqlset cn = server.CreateObject("adodb.connection")cn.Open cnstrset rs = server.CreateObject("adodb.recordset")sql = "select * from tblImage"rs.Open sql,cn,1,3rs.AddNewrs.Fields("content-type").Value = strContentTypers.Fields("image").AppendChunk strDatars.Updaters.Closeset rs = nothingcn.Closeset cn = nothingresponse.Write "图片保存成功!" & "<br>"elseresponse.Write "没有上传图片!" & "<br>"end ifset sGo = nothingsCome.Closeset sCome = nothingelse%><form id="frmUpload" name="frmUpload" action="SimpleImageToData.asp" method="post" target="_self" enctype="multipart/form-data"><INPUT id="filImage" type="file" name="filImage" size="40"><BR><INPUT id="btnUpload" type="submit" value="Upload" name="btnUpload"> </form><%end if%></body></HTML>3、ShowImageListFromData.asp<%@ Language=VBScript %><% option explicit %><html><head><title>显示数据库中已有图片的列表</title><meta http-equiv="Content-Type" content="text/html; charset=gb2312"> </head><body><p><a href="SimpleImageToData.asp">上传图片</a><a href="ShowImageListFromData.asp">显示图片</a><hr></p><table border=0 cellpadding=2 cellspacing=2><tr><td valign=top><%dim cnstrcnstr = "driver={Microsoft Access Driver (*.mdb)};dbq=" &server.MapPath("./upload.mdb")dim cn, sql, rsset cn = server.CreateObject("adodb.connection")cn.Open cnstrsql = "select sn,[content-type],image from tblImage"set rs = cn.Execute(sql)response.Write "<table border=1 cellspacing=2 cellpadding=5>"response.Write "<tr>"response.Write "<th>序列号</th><th>图片类型</th><th>图片</th>"response.Write "</tr>"do until rs.eofresponse.Write "<tr>"response.Write "<td>" & rs("sn") & "</td>"response.Write "<td>" & rs("content-type") & "</td>"response.Write "<td><a href='ShowImageListFromData.asp?sn=" &rs("sn") & "'>看图</a></td>"response.Write "</tr>"rs.movenextloopresponse.Write "</table>"cn.Closeset cn = nothing%></td><td valign=top><%dim snsn = request.QueryString("sn")if sn = "" thenresponse.Write "没有指定图片!"elseresponse.Write "<img border=1 src=ShowImageFromData.asp?sn=" & sn & ">"end if%></td></tr></table></body></html>4、ShowImageFromData.asp<%@ Language=VBScript %><% option explicit %><%dim snsn = request.QueryString("sn")if sn = "" then response.Enddim cnstrcnstr = "driver={Microsoft Access Driver (*.mdb)};dbq=" &server.MapPath("./upload.mdb")dim cn, sql, rsset cn = server.CreateObject("adodb.connection")cn.Open cnstrsql = "select sn,[content-type],image from tblImage where sn=" & cint(sn) set rs = cn.Execute(sql)response.ContentType = rs("content-type")response.BinaryWrite rs("image")set rs = nothingcn.Closeset cn = nothing%>。

相关文档
最新文档