上传图片后使用数据库保存图片的示例分享
httppostedfile upfile = file1.postedfile;
int filelenght = upfile.contentlength;
decimal filesize = filelenght / 1024;
if (filelenght == 0)
{
divshowgverror.visible = true;
lblshowgverror.text = "请选择上传文件";
return;
}
string strimagename = upfile.filename;
string strimagetype = strimagename.substring(strimagename.lastindexof(".")).tolower();
if (strimagetype != ".jpg" && strimagetype != ".jpeg" && strimagetype != ".bmp" && strimagetype != ".png")
{
divshowgverror.visible = true;
lblshowgverror.text = "請上傳以下文件格式的圖片:jpg,jpeg,bmp,png";
return;
}
if (filesize > 2048)
{
divshowgverror.visible = true;
lblshowgverror.text = "上傳圖片不能大於2m";
return;
}
else
{
byte[] filebytearray = new byte[filelenght];
stream streamobject = upfile.inputstream;
streamobject.read(filebytearray, 0, filelenght);
strnewleave = "insert into [leave]([id],[employeeno],[agentid],[leavetype],[startdate],[enddate],[hours],[leavereason],[reporttime],[reportid],[imagename],[imagedata]) ";
strnewleave += "values(@leaveno,@empno,@agentname,@leatype,@startdate,@enddate,@hours,@reason,getdate(),@admin,@imagename,@image) ";
sqlpara = new sqlparameter[] {
new sqlparameter("@leaveno",strleano),
new sqlparameter("@empno",strempno),
new sqlparameter("@agentname",stragentid),
new sqlparameter("@leatype",strleatype),
new sqlparameter("@startdate",strdatest),
new sqlparameter("@enddate",strdateend),
new sqlparameter("@hours",strhours),
new sqlparameter("@reason",strreason),
new sqlparameter("@admin",stradmin),
new sqlparameter("@imagename",strimagename),
new sqlparameter("@image",filebytearray)
};
streamobject.close();
}
sqlhelper sqlh = new sqlhelper();
string strid = context.request["id"];
byte[] mydata = new byte[0];
string str = " select [imagedata] from [leave] where [id]='" + strid + "' ";
datatable dt = sqlh.executequery(str, commandtype.text);
if (dt.rows.count > 0)
{
mydata = (byte[])dt.rows[0][0];
int arraysize = mydata.getupperbound(0);
context.response.outputstream.write(mydata, 0, arraysize);
}