当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net下将图片保存到XML文件的方法

asp.net下将图片保存到XML文件的方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

英锦赛赛程,军中绿花串词,凶猛鱼类

一.保存图片到xml文件
复制代码 代码如下:

/// <summary>
/// 保存图片到xml文件
/// </summary>
private void uploadimagetoxml()
{
///得到用户要上传的文件名
string strfilepathname = lofile.postedfile.filename;
string strfilename = path.getfilename(strfilepathname);
int filelength = lofile.postedfile.contentlength;
if(filelength<=0)
return;
try
{
///图象文件临时储存byte数组
byte[] filebytearray = new byte[filelength];

///建立数据流对像
stream streamobject = lofile.postedfile.inputstream;

///读取图象文件数据,filebytearray为数据储存体,0为数据指针位置、filelnegth为数据长度
streamobject.read(filebytearray,0,filelength);

///要打开的文件
string filename = server.mappath(".\\writexml.xml");

xmldocument xmldoc = new xmldocument();
xmldoc.load(filename);

///查找<dbguest>
xmlnode root=xmldoc.selectsinglenode("dbimage");
xmlnodelist xnl=xmldoc.selectsinglenode("dbimage").childnodes;
int nindex = xnl.count;

///以下添加新结点
xmlelement xe1=xmldoc.createelement("image");//创建一个<user>节点
xmlelement xesub1=xmldoc.createelement("imageid");

///设置文本节点
xesub1.innertext=nindex.tostring();

///添加到<user>节点中
xe1.appendchild(xesub1);
xmlelement xesub2=xmldoc.createelement("imagecontenttype");
xesub2.innertext=lofile.postedfile.contenttype;
xe1.appendchild(xesub2);
xmlelement xesub3=xmldoc.createelement("imagesize");
xesub3.innertext=filelength.tostring();
xe1.appendchild(xesub3);
xmlelement xesub4=xmldoc.createelement("imagedescription");
xesub4.innertext=tbdescription.text;
xe1.appendchild(xesub4);
xmlelement xesub5=xmldoc.createelement("imagedata");
xesub5.innertext= convert.tobase64string(filebytearray);
xe1.appendchild(xesub5);

///添加到<dbguest>节点中
root.appendchild(xe1);
xmldoc.save(filename);

response.redirect("showallimg.aspx");
}
catch(exception ex)
{
throw ex;
}
}

二.从xml中读取图片数据

复制代码 代码如下:

/// <summary>
/// 从xml中读取图片
/// </summary>
/// <param name="imageid">图片id</param>
private void readimagefromxml(string imageid)
{
///id为图片id
int imgid = convert.toint32(imageid);

///要打开的文件
string filename = server.mappath(".\\writexml.xml");

xmldocument xmldoc = new xmldocument();
xmldoc.load(filename);
xmlnodelist node = xmldoc.selectsinglenode("//image[imageid='"+imgid.tostring()+"']").childnodes;
if(node!=null)
{
string strtype = node.item(1).innertext;
string strdata =node.item(4).innertext;
int nsize = int.parse(node.item(2).innertext);

///设定输出文件类型
response.contenttype = strtype;

///输出图象文件二进制数制
response.outputstream.write(convert.frombase64string(strdata), 0, nsize);
response.end();

//也可以保存为图像
//filestream fs = new filestream(@"c:\aa.bmp", filemode.openorcreate, fileaccess.write);
//fs.write((convert.frombase64string(strdata), 0,nsize);
//fs.close();
}
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网