您的位置:首页 > 数据库

C#写入/读取SqlServer图片

2009-05-05 10:06 155 查看
1.SqlServer存储过程

ALTER proc UploadAgentDealerApplyConsent

@ID int,

@ApplyConsent image

/*

功能:上传指定代理商的申请单位承诺[图]

参数:

@ID 代理商信息编号

@ApplyConsent 要上传的申请单位承诺[图]

*/

as

begin

update AgentDealerInfo

set ApplyConsent = @ApplyConsent

where [id] = @ID

end

ALTER proc GetAgentDealerApplyConsent

@ID int

/*

功能:根据代理商信息编号获得其申请单位承诺[图]

参数

@ID 代理商信息编号

*/

as

begin

select ApplyConsent from AgentDealerInfo where [ID] = @ID

end

2.上传图片到数据库

protected void BtnSubmit_Click(object sender, EventArgs e)

{

if (Page.IsValid)

{

using (WorkDataBaseBusiness dataBase = new WorkDataBaseBusiness())

{

//得到提交的文件

Stream fileDataStream = FileUpload1.PostedFile.InputStream;

//创建数组

byte[] fileData = new byte[FileUpload1.PostedFile.ContentLength];

//把文件流填充到数组

fileDataStream.Read(fileData, 0, fileData.Length);

//这里使用存储过程写入数据库

SqlParameter[] sqlParams = {

dataBase.MakeInParam("@ID",SqlDbType.Int,0,infoID),

dataBase.MakeInParam("@ApplyConsent",SqlDbType.Image,0,fileData)

};

try

{

dataBase.RunProc("UploadAgentDealerApplyConsent", sqlParams);

Response.Write("<script>alert('上传申请单位承诺[图]成功.');top.location='../index.aspx';</script>");

Response.End();

}

catch

{

Response.Write("<script>alert('上传申请单位承诺[图]失败.请稍候重试.');</script>");

}

}

}

}

3.图片显示的页面[这里使用Session保存字节数组]

//缓存图像字节流关键字

private const string KEY_CACHE_IMAGE = "CacheImage";

protected void Page_Load(object sender, EventArgs e)

{

try

{

byte[] fileData = (byte[])Session[KEY_CACHE_IMAGE];

MemoryStream stream = new MemoryStream(fileData, true);

stream.Write(fileData, 0, fileData.Length);

Bitmap image = new Bitmap(stream);

image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

}

catch

{

Response.Write("图片读取失败.");

}

}

4.读取数据库图片并显示到页面

using (WorkDataBaseBusiness dataBase = new WorkDataBaseBusiness())

{

SqlParameter[] sqlParams = {

dataBase.MakeInParam("@ID",SqlDbType.Int,0,infoID)

};

dataBase.RunProc("GetAgentDealerApplyConsent", sqlParams, out ds);

}

if (ds.Tables[0].Rows.Count > 0)

{

byte[] fileData = (byte[])ds.Tables[0].Rows[0]["ApplyConsent"];

Session[KEY_CACHE_IMAGE] = fileData;

Image1.ImageUrl = "../inc/Image.aspx";

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: