ASP.NET学习基础十五:上传图片到数据库

首先、在WEBFORMHTML中将FORM的属性修改为如下:

<form id="Form1" method="post"enctype="multipart/form-data" runat="server">

然后在保存到数据库的按钮中写

string imgtype = myFile.PostedFile.ContentType;

string imgtitle = TextBox1.Text;

Stream imgdatastream = myFile.PostedFile.InputStream;

int imgdatalen = myFile.PostedFile.ContentLength;

byte[] imgdata = new byte[imgdatalen];

int n = imgdatastream.Read(imgdata,0,imgdatalen);

string connstr="server=new;uid=sa;pwd=sa;database=dianxinkapin";//

SqlConnection connection = new SqlConnection(connstr);

SqlCommand command = new SqlCommand("INSERT INTO ImageStore(id,imgtitle,imgtype,imgdata) VALUES (@id, @imgtitle, @imgtype,@imgdata )", connection );

command.Parameters.Add("@id", SqlDbType.VarChar,50).Value= TextBox1.Text;

command.Parameters.Add("@imgtitle", SqlDbType.VarChar,50).Value= TextBox2.Text;

command.Parameters.Add("@imgdata", SqlDbType.Image).Value= imgdata;

command.Parameters.Add("@imgtype", SqlDbType.VarChar,50).Value= imgtype;

connection.Open();

int numRowsAffected = command.ExecuteNonQuery();

  connection.Close();

if(myFile.PostedFile!=null)

{

string nam = myFile.PostedFile.FileName ;  

int i= nam.LastIndexOf("\\") ;

string newnm =nam.Substring(i) ;

 

if(File.Exists(Server.MapPath("image\\")+newnm))//判断文件是否存在

{

Label1.Text="此文件名在服务器上已存在!!";

}

myFile.PostedFile.SaveAs(Server.MapPath("image\\")+newnm) ;

TextBox1.Text=myFile.PostedFile.FileName;

 

TextBox2.Text=myFile.PostedFile.ContentType ;

TextBox3.Text=myFile.PostedFile.ContentLength.ToString();

  }

在浏览图片的按钮下写

string connstr="server=new;uid=sa;pwd=sa;database=dianxinkapin";

  string sql="SELECT imgdata, imgtype FROM ImageStore WHERE id ='"+TextBox1.Text+"'"; 

  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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值