初学的小菜鸟提问了,请各位大师指教.(把图片上传到数据库的问题)

问题描述

stringfilename=null;filename=this.File1.PostedFile.FileName;filename=filename.Substring(filename.LastIndexOf("\")+1);Session["photo"]=filename=System.DateTime.Now.ToString("yyyyMMddhhmmss")+filename;this.File1.PostedFile.SaveAs(Server.MapPath("up")+@""+filename);Response.Write("<script>alert('上传成功!')</script>");SqlConnectioncon=newSqlConnection("server=.;database=Users;uid=sa;pwd=123");con.Open();SqlCommandcmd=newSqlCommand("insertintoshowvalues('"+this.TextBox1.Text+"','"+Session["photo"]+"')",con);cmd.ExecuteNonQuery();con.Close();我想把图片(名)上传到数据库,这样行吗?然后怎么到数据库中提取并显示呢????

解决方案

解决方案二:
你这种方法我可没试过,应该不可以ASP.NET如何存取SQLServer数据库图片  SQLServer提供了一个特别的数据类型:image,它是一个包含binary数据的类型。下边这个例子就向你展示了如何将文本或照片放入到数据库中的办法。在这篇文章中我们要看到如何在SQLServer中存储和读取图片。  1、建立一个表:  在SQLSERVER中建立这样结构的一个表:列名类型目的IDInteger主键IDIMGTITLEVarchar(50)图片的标题IMGTYPEVarchar(50)图片类型.ASP.NET要以辨认的类型IMGDATAImage用于存储二进制数据  2、存储图片到SQLSERVER数据库中  为了能存储到表中,你首先要上传它们到你的WEB服务器上,你可以开发一个webform,它用来将客户端中TextBoxwebcontrol中的图片入到你的WEB服务器上来。将你的encType属性设置为:myltipart/formdata.Streamimgdatastream=File1.PostedFile.InputStream;intimgdatalen=File1.PostedFile.ContentLength;stringimgtype=File1.PostedFile.ContentType;stringimgtitle=TextBox1.Text;byte[]imgdata=newbyte[imgdatalen];intn=imgdatastream.Read(imgdata,0,imgdatalen);stringconnstr=((NameValueCollection)Context.GetConfig("appSettings"))["connstr"];SqlConnectionconnection=newSqlConnection(connstr);SqlCommandcommand=newSqlCommand         ("INSERTINTOImageStore(imgtitle,imgtype,imgdata)         VALUES(@imgtitle,@imgtype,@imgdata)",connection);SqlParameterparamTitle=newSqlParameter         ("@imgtitle",SqlDbType.VarChar,50);paramTitle.Value=imgtitle;command.Parameters.Add(paramTitle);SqlParameterparamData=newSqlParameter("@imgdata",SqlDbType.Image);paramData.Value=imgdata;command.Parameters.Add(paramData);SqlParameterparamType=newSqlParameter("@imgtype",SqlDbType.VarChar,50);paramType.Value=imgtype;command.Parameters.Add(paramType);connection.Open();intnumRowsAffected=command.ExecuteNonQuery();connection.Close();  3、从数据库中恢复读取  现在让我们来从SQLServer中读取我们放入的数据吧!我们将要输出图片到你的浏览器上,你也可以将它存放到你要的位置。privatevoidPage_Load(objectsender,System.EventArgse){ stringimgid=Request.QueryString["imgid"]; stringconnstr=((NameValueCollection) Context.GetConfig("appSettings"))["connstr"]; stringsql="SELECTimgdata,imgtypeFROMImageStoreWHEREid="+imgid; SqlConnectionconnection=newSqlConnection(connstr); SqlCommandcommand=newSqlCommand(sql,connection); connection.Open(); SqlDataReaderdr=command.ExecuteReader(); if(dr.Read()) {  Response.ContentType=dr["imgtype"].ToString();  Response.BinaryWrite((byte[])dr["imgdata"]); } connection.Close();}  要注意的是Response.BinaryWrite而不是Response.Write.
解决方案三:
下面给大家一个用于C#Winform的存入、读取程序。其中不同请大家自己比较!(为了方便起见,我将数据库字段简化为二个:imgtitle和imgdata。usingSystem;usingSystem.Drawing;usingSystem.Collections;usingSystem.ComponentModel;usingSystem.Windows.Forms;usingSystem.Data;usingSystem.IO;usingSystem.Data.SqlClient;namespaceWindowsApplication21{ ///<summary> ///Form1的摘要说明。 ///</summary> publicclassForm1:System.Windows.Forms.Form {  privateSystem.Windows.Forms.Buttonbutton1;  ///<summary>  ///必需的设计器变量。  ///</summary>  privateSystem.ComponentModel.Containercomponents=null;  privatestringConnectionString="IntegratedSecurity=SSPI;InitialCatalog=;Data Source=localhost;";  privateSqlConnectionconn=null;  privateSqlCommandcmd=null;  privateSystem.Windows.Forms.Buttonbutton2;  privateSystem.Windows.Forms.PictureBoxpic1;  privateSystem.Windows.Forms.OpenFileDialogopenFileDialog1;  privatestringsql=null;  privateSystem.Windows.Forms.Labellabel2;  privatestringnowId=null; publicForm1() {  //  //Windows窗体设计器支持所必需的  //  InitializeComponent();  conn=newSqlConnection(ConnectionString);  //  //TODO:在InitializeComponent调用后添加任何构造函数代码  // } ///<summary> ///清理所有正在使用的资源。 ///</summary> protectedoverridevoidDispose(booldisposing) {  if(conn.State==ConnectionState.Open)   conn.Close();  if(disposing)  {   if(components!=null)   {    components.Dispose();   }  }  base.Dispose(disposing); } #regionWindowsFormDesignergeneratedcode ///<summary> ///设计器支持所需的方法-不要使用代码编辑器修改 ///此方法的内容。 ///</summary> privatevoidInitializeComponent() {  this.button1=newSystem.Windows.Forms.Button();  this.pic1=newSystem.Windows.Forms.PictureBox();  this.button2=newSystem.Windows.Forms.Button();  this.openFileDialog1=newSystem.Windows.Forms.OpenFileDialog();  this.label2=newSystem.Windows.Forms.Label();  this.SuspendLayout();  //  //button1  //  this.button1.Location=newSystem.Drawing.Point(0,40);  this.button1.Name="button1";  this.button1.Size=newSystem.Drawing.Size(264,48);  this.button1.TabIndex=0;  this.button1.Text="加入新的图片";  this.button1.Click+=newSystem.EventHandler(this.button1_Click);  //  //pic1  //  this.pic1.Location=newSystem.Drawing.Point(280,8);  this.pic1.Name="pic1";  this.pic1.Size=newSystem.Drawing.Size(344,264);  this.pic1.TabIndex=3;  this.pic1.TabStop=false;  //  //button2  //  this.button2.Location=newSystem.Drawing.Point(0,104);  this.button2.Name="button2";  this.button2.Size=newSystem.Drawing.Size(264,40);  this.button2.TabIndex=4;  this.button2.Text="从数据库中恢复图像";  this.button2.Click+=newSystem.EventHandler(this.button2_Click);  //  //openFileDialog1  //  this.openFileDialog1.Filter=""图像文件(*.jpg,*.bmp,*.gif)|*.jpg|*.bmp|*.gif"";  //  //label2  //  this.label2.Location=newSystem.Drawing.Point(0,152);  this.label2.Name="label2";  this.label2.Size=newSystem.Drawing.Size(264,48);  this.label2.TabIndex=5;  //  //Form1  //  this.AutoScaleBaseSize=newSystem.Drawing.Size(6,14);  this.ClientSize=newSystem.Drawing.Size(632,273);  this.Controls.AddRange(newSystem.Windows.Forms.Control[]{    this.label2,    this.button2,    this.pic1,    this.button1});  this.Name="Form1";  this.Text="Form1";  this.Load+=newSystem.EventHandler(this.Form1_Load);  this.ResumeLayout(false); } #endregion  ///<summary> ///应用程序的主入口点。 ///</summary> [STAThread] staticvoidMain() {  Application.Run(newForm1()); } privatevoidbutton1_Click(objectsender,System.EventArgse) {  openFileDialog1.ShowDialog();    if(openFileDialog1.FileName.Trim()!="")  {   FileInfofi=newFileInfo(openFileDialog1.FileName);   stringimgtitle=openFileDialog1.FileName;   intimgdatalen=(int)fi.Length;   byte[]imgdata=newbyte[imgdatalen];     Streamimgdatastream=fi.OpenRead();   intn=imgdatastream.Read(imgdata,0,imgdatalen);   if(conn.State==ConnectionState.Open)    conn.Close();   ConnectionString="IntegratedSecurity=SSPI;"+"InitialCatalog=mydb;"+"Data Source=localhost;";   conn.ConnectionString=ConnectionString; try {  stringmySelectQuery="INSERTINTOImageStore(imgtitle,imgdata)VALUES(@imgtitle,@imgdata)";  //stringmySelectQuery="UPDATEImageStoresetimgtitle=@imgtitle,imgdata=@imgdata";  SqlCommandmyCommand=newSqlCommand(mySelectQuery,conn);  SqlParameterparamTitle=newSqlParameter("@imgtitle",SqlDbType.VarChar,50);  paramTitle.Value=imgtitle;  myCommand.Parameters.Add(paramTitle);  SqlParameterparamData=newSqlParameter("@imgdata",SqlDbType.Image);  paramData.Value=imgdata;  myCommand.Parameters.Add(paramData);  conn.Open();  intnumRowsAffected=myCommand.ExecuteNonQuery();  conn.Close(); } catch(Exceptionerr) {  MessageBox.Show("您输入名称可能在数据库中已存在或输入为空,请检查!"+err.ToString()); } finally {}}} privatevoidForm1_Load(objectsender,System.EventArgse) { } privatevoidbutton2_Click(objectsender,System.EventArgse) {  //打开数据库连接  if(conn.State==ConnectionState.Open)   conn.Close();  ConnectionString="IntegratedSecurity=SSPI;"+"InitialCatalog=mydb;"+"DataSource=localhost;";  conn.ConnectionString=ConnectionString;  //创建数据适配器  stringsql="SELECT*FROMImageStore";  SqlCommandcommand=newSqlCommand(sql,conn);   try  {conn.Open();}  catch(Exceptionnewerr)  {   MessageBox.Show("不能打开数据联接!");  }  finally  {}  SqlDataReaderdr=command.ExecuteReader();  if(dr.Read())  {   FileInfofi=newFileInfo("temp");   FileStreammyStream=fi.Open(FileMode.Create);   byte[]mydata=((byte[])dr["imgdata"]);   //label2.Text="您现在看到的是:"+dr["imgtitle"].ToString();   foreach(byteainmydata)   {    myStream.WriteByte(a);   }  myStream.Close();  ImagemyImage=Image.FromFile("temp");  pic1.Image=myImage;  pic1.Refresh();  dr.Close(); } else {  MessageBox.Show("没有成功读入数据!");  } conn.Close();}}}
解决方案四:
在网站上面新建立一个文件夹用于存放图片。数据库存放图片名称!读文件夹名+图片名称就可以了在上传的时候注意,注意压缩比例!
解决方案五:
楼上正解
解决方案六:
收藏

时间: 2024-09-15 06:04:23

初学的小菜鸟提问了,请各位大师指教.(把图片上传到数据库的问题)的相关文章

专家请进,C#的图片上传

问题描述 我想在C#里实现图片和文字的一块上传,用一个button来实现,怎么弄,能不能说的详细点,我是新手! 解决方案 解决方案二:帮你顶下!解决方案三:C/S:B/S:解决方案四:在button事件中,先把文件上传保存到服务器端,接着再将信息存储到数据库的表中.解决方案五:是想合成一个image上传,还是要分开成上传到一块啊...你看下给image写文件注释试试..

编程c语言-求助!菜鸟一枚 请大神指教!

问题描述 求助!菜鸟一枚 请大神指教! 请问用c语言怎么计算校验和?能将带有汉字的文件读入然后计算?过程怎么写!好着急啊! 解决方案 文件不管有没有汉字,都当作二进制数据.校验和还分为不同位数的. 具体要看对方协议的要求 仅供参考:http://download.csdn.net/detail/captain_black/679608 解决方案二: 1.中文字符串可以使用printf().puts()等函数直接输出.#include #include int main(){ const char

session-KindEditor批量图片上传,SESSION丢失!4.1.10.jsp请大神帮忙解决一下

问题描述 KindEditor批量图片上传,SESSION丢失!4.1.10.jsp请大神帮忙解决一下 后台使用的jsp,批量上传图片时session取到的值为null,如何将之前的session传到jsp后台中 String dataSource = (String)request.getSession().getAttribute(SaasConstant.DATA_SOURCE);其中SaasConstant.DATA_SOURCE是存放在session中的

菜鸟提问。请多多帮忙

问题描述 for(i=0;i<maps.length;i++){beginX=0;beginY=0;nX=maps[i].x%maps[i].tileSize;//为什么这样算这是nx是什么nY=maps[i].y%maps[i].tileSize;while(true){while(true){//ifarray'snumis0xff,mapisnotdraw;tempY=((beginX+maps[i].x)/maps[i].tileSize)%maps[i].w;//不明白.为什么这样te

c#菜鸟提问,请多多指教

问题描述 srMyfile.BaseStream.Seek(0,SeekOrigin.Begin)请问上面语句中的0是什么作用,可以改为其它值吗? 解决方案 解决方案二:srMyfile是一个BinaryReader吗?BinaryReader.BaseStream返回的是一个Stream基础流对象Seek是用来设置当前流中的位置Stream.Seek(longoffset,SeekOriginorigin)其中origin是一个枚举,可以是当前位置Current,结束位置End,SeekOri

J2ME实现手机图片上传的一些小经验

这几天研究j2me图片文件上传,手机上用FileConnection浏览文件夹,读取图片文件, 然后提交到服务器上的http接口. 首先采用的是 HttpConnection ,发送数据(构建文件上传方式也一样), 发现数据都被采用了 chunked 编码, 服务端什么内容都获取不到( 这里遇到一个奇怪的问题,用我本机做服务端,即使chunked编码,也能够完整的获取到数据), chunked只有在数据超过2016个字节的时候才会产生. 于是上网搜集资料,发现mingjava的colala实例采

图片上传问题,请各位给个思路

问题描述 我在项目中碰到这样一个问题:用手机拍照,然后上传至服务器(说明:照片大小是确定的15K,但数量不确定),但速度不是很理想我现在的解决方法是:一个HttpConnection连接传几张图片.希望各位给个好的解决办法,能提高速度. 解决方案 解决方案二:http://blog.csdn.net/javaxiaochouyu/archive/2011/04/28/6370655.aspx或许对你有些帮助...解决方案三:谢谢楼上的.我想要的是手机端处理的思路

菜鸟提问如何点击一个button弹出一个日历页面

问题描述 问题两个第一个是在Button_Click里面怎样写,c#的哦另外一个是如何定义弹出来的那个窗口的尺寸,我想要小小一个页面我是菜鸟mm,请大家多多指教,有用msn的吗我的msn是liuxing515@hotmail.com欢迎有时间的人加我探讨.net的问题 解决方案 解决方案二:privatevoidbutton1_Click(objectsender,EventArgse){Formf=newForm();MonthCalendarmm=newMonthCalendar();f.H

求达人指教小菜鸟

问题描述 本人未毕业小菜鸟MM一枚求达人指教struts1和struts2中的action配置有需要加本人QQ542211593 解决方案 解决方案二: 解决方案三:楼主有那么可爱吗?一枚解决方案四:引用2楼haorengoodman的回复: 楼主有那么可爱吗?一枚 ++++++解决方案五: 解决方案六: 解决方案七:关于struts的配置,网上资料非常多.随便一搜就有,MM加油啊.解决方案八:action配置???web.xml配置,还是struts.xml配置.解决方案:可以看看这个:解决方