欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

将图片写入数据库并显示出来

程序员文章站 2024-01-19 13:50:46
...
using System;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace UploadImage
{
public class UploadImage:Page{
protected HtmlInputFile up_file;
protected TextBox txtDescription;
protected Label txtMessage;
protected Int32 fileLength=0;
protected void Button_Submit(System.Object sender,System.EventArgs e){
HttpPostedFile UpFile=up_file.PostedFile;
fileLength=UpFile.ContentLength;
try{
if(fileLength==0){
txtMessage.Text="<b>请你选择你要上传的文件</b>";
}
else{
Byte[] FileByteArray=new Byte[fileLength];
Stream StreamObject=UpFile.InputStream;
StreamObject.Read(FileByteArray,0,fileLength);
SqlConnection Con=new SqlConnection("Data Source=Localhost;Initial Catalog=DBImages;uid=sa;pwd=;");
string SqlCmd="insert into image(ImageData,ImageContentType,ImageDescription,ImageSize)values(@Image,@ContentType,@ImageDescription,@ImageSize)";
SqlCommand CmdObj=new SqlCommand(SqlCmd,Con);
CmdObj.Parameters.Add("@Image",SqlDbType.Binary,fileLength).Value=FileByteArray;
CmdObj.Parameters.Add("@ContentType",SqlDbType.VarChar,50).Value=UpFile.ContentType;
CmdObj.Parameters.Add("@ImageDescription",SqlDbType.VarChar,200).Value=txtDescription.Text;
CmdObj.Parameters.Add("@ImageSize",SqlDbType.BigInt,8).Value=UpFile.ContentLength;
Con.Open();
CmdObj.ExecuteNonQuery();
Con.Close();
txtMessage.Text="<p><b>OK!你已经成功上传你的图片</b>";
}
}
catch(Exception ex){
txtMessage.Text=ex.Message.ToString();
}
}
}
}
______________________________________________________________________________________________
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace ReadImage{
public class MainDisplay:System.Web.UI.Page{
void Page_Load(System.Object sender,System.EventArgs e){
int ImgID=Convert.ToInt32(Request.QueryString["ImgID"]);
SqlConnection Con=new SqlConnection("Data Source=localhost;Initial Catalog=DBImages;uid=sa;pwd=;");
string SqlCmd="select * from image where ";
SqlCommand CmdObj=new SqlCommand(SqlCmd,Con);
CmdObj.Parameters.Add("@ImageID",SqlDbType.Int).Value=ImgID;
Con.Open();
SqlDataReader SqlReader=CmdObj.ExecuteReader();
if(SqlReader.Read()){
Response.ContentType=(string)SqlReader["ImageContentType"];
Response.BinaryWrite((byte[])SqlReader["ImageData"]);
}
Con.Close();
}
}
}