Web Service上传下载文件[1]

[入库:2005年8月18日] [更新:2007年3月25日]

本文简介:选择自 cloud_soft 的 blog

通过web services上传和下载文件
作者:孟宪会 出自:【孟宪会之精彩世界】 发布日期:2003年11月24日 2点1分31秒

随着internet技术的发展和跨平台需求的日益增加,web services的应用越来越广,我们不但需要通过web services传递字符串信息,而且需要传递二进制文件信息。下面,我们就分别介绍如何通过web services从服务器下载文件到客户端和从客户端通过web services上载文件到服务器。

一:通过web services显示和下载文件

我们这里建立的web services的名称为getbinaryfile,提供两个公共方法:分别是getimage()和getimagetype(),前者返回二进制文件字节数组,后者返回文件类型,其中,getimage()方法有一个参数,用来在客户端选择要显示或下载的文件名字。这里我们所显示和下载的文件可以不在虚拟目录下,采用这个方法的好处是:可以根据权限对文件进行显示和下载控制,从下面的方法我们可以看出,实际的文件位置并没有在虚拟目录下,因此可以更好地对文件进行权限控制,这在对安全性有比较高的情况下特别有用。这个功能在以前的asp程序中可以用stream对象实现。为了方便读者进行测试,这里列出了全部的源代码,并在源代码里进行介绍和注释。

首先,建立getbinaryfile.asmx文件:

我们可以在vs.net里新建一个c#的aspxwebcs工程,然后“添加新项”,选择“web服务”,并设定文件名为:getbinaryfile.asmx,在“查看代码”中输入以下代码,即:getbinaryfile.asmx.cs:

using system; using system.collections; using system.componentmodel; using system.data; using system.diagnostics; using system.web; using system.web.ui; using system.web.services; using system.io; namespace xml.sz.luohuedu.net.aspxwebcs { /// <summary> /// getbinaryfile 的摘要说明。 /// web services名称:getbinaryfile /// 功能:返回服务器上的一个文件对象的二进制字节数组。 /// </summary> [webservice(namespace="http://xml.sz.luohuedu.net/", description="在web services里利用.net框架进行传递二进制文件。")] public class getbinaryfile : system.web.services.webservice { #region component designer generated code //web 服务设计器所必需的 private icontainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> protected override void dispose( bool disposing ) { if(disposing && components != null) { components.dispose(); } base.dispose(disposing); } #endregion public class images: system.web.services.webservice { /// <summary> /// web 服务提供的方法,返回给定文件的字节数组。 /// </summary> [webmethod(description="web 服务提供的方法,返回给定文件的字节数组")] public byte[] getimage(string requestfilename) { ///得到服务器端的一个图片 ///如果你自己测试,注意修改下面的实际物理路径 if(requestfilename == null || requestfilename == "") return getbinaryfile("d:\\picture.jpg"); else return getbinaryfile("d:\\" + requestfilename); } /// <summary> /// getbinaryfile:返回所给文件路径的字节数组。 /// </summary> /// <param name="filename"></param> /// <returns></returns> public byte[] getbinaryfile(string filename) { if(file.exists(filename)) { try { ///打开现有文件以进行读取。 filestream s = file.openread(filename); return convertstreamtobytebuffer(s); } catch(exception e) { return new byte[0]; } } else { return new byte[0]; } } /// <summary> /// convertstreamtobytebuffer:把给定的文件流转换为二进制字节数组。 /// </summary> /// <param name="thestream"></param> /// <returns></returns> public byte[] convertstreamtobytebuffer(system.io.stream thestream) { int b1; system.io.memorystream tempstream = new system.io.memorystream(); while((b1=thestream.readbyte())!=-1) { tempstream.writebyte(((byte)b1)); } return tempstream.toarray(); } [webmethod(description="web 服务提供的方法,返回给定文件类型。")] public string getimagetype() { ///这里只是测试,您可以根据实际的文件类型进行动态输出 return "image/jpg"; } } } }

一旦我们创建了上面的asmx文件,进行编译后,我们就可以编写客户端的代码来进行调用这个web services了。

我们先“添加web引用”,输入:http://localhost/aspxwebcs/getbinaryfile.asmx。下面,我们编写显示文件的中间文件:getbinaryfileshow.aspx,这里,我们只需要在后代码里编写代码即可,getbinaryfileshow.aspx.cs文件内容如下:

using system; using system.collections; using system.componentmodel; using system.data; using system.drawing; using system.web; using system.web.sessionstate; using system.web.ui; using system.web.ui.webcontrols; using system.web.ui.htmlcontrols; using system.web.services; namespace aspxwebcs { /// <summary> /// getbinaryfileshow 的摘要说明。 /// </summary> public class getbinaryfileshow : system.web.ui.page { private void page_load(object sender, system.eventargs e) { // 在此处放置用户代码以初始化页面 ///定义并初始化文件对象; xml.sz.luohuedu.net.aspxwebcs.getbinaryfile.images oimage; oimage = new xml.sz.luohuedu.net.aspxwebcs.getbinaryfile.images(); ///得到二进制文件字节数组; byte[] image = oimage.getimage(""); ///转换为支持存储区为内存的流 system.io.memorystream memstream = new system.io.memorystream(image); ///定义并实例化bitmap对象 bitmap bm = new bitmap(memstream); ///根据不同的条件进行输出或者下载; response.clear(); ///如果请求字符串指定下载,就下载该文件; ///否则,就显示在浏览器中。 if(request.querystring["download"]=="1") { response.buffer = true; response.contenttype = "application/octet-stream"; ///这里下载输出的文件名字 ok.jpg 为例子,你实际中可以根据情况动态决定。 response.addheader("content-disposition","attachment;filename=ok.jpg"); } else response.contenttype = oimage.getimagetype(); response.binarywrite(image); response.end(); } #region web form designer generated code override protected void oninit(eventargs e) { // // codegen:该调用是 asp.net web 窗体设计器所必需的。 // initializecomponent(); base.oninit(e); } /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void initializecomponent() { this.load += new system.eventhandler(this.page_load); } #endregion } }

最后,我们就编写最终的浏览页面:getbinaryfile.aspx,这个文件很简单,只需要aspx文件即可,内容如下:

<%@ page language="c#" codebehind="getbinaryfile.aspx.cs" autoeventwireup="false" inherits="aspxwebcs.getbinaryfile" %> <!doctype html public "-//w3c//dtd html 4.0 transitional//en" > <html> <head> <title>通过web services显示和下载文件</title> <meta name="generator" content="microsoft visual studio 7.0"> <meta name="code_language" content="c#"> <meta name="vs_defaultclientscript" content="javascript"> <meta name="vs_targetschema" content="http://schemas.microsoft.com/intellisense/ie5"> </head> <body ms_positioning="gridlayout"> <form id="getbinaryfile" method="post" runat="server"> <font face="宋体"> <asp:hyperlink id="hyperlink1" navigateurl="getbinaryfileshow.aspx?download=1" runat="server">下载文件</asp:hyperlink> <br/> <!--下面是直接显示文件--> <asp:image id="image1" imageurl="getbinaryfileshow.aspx" runat="server"></asp:image> </font> </form> </body> </html>

二:通过web services上载文件

向服务器上载文件可能有许多种方法,在利用web services上载文件的方法中,下面的这个方法应该是最简单的了。我们仍象前面的例子那样,首先建立upload.asmx文件,其upload.asmx.cs内容如下,里面已经做了注释:

using system; using system.collections; using system.componentmodel; using system.data; using system.diagnostics; using system.web; using system.web.services; using system.io; namespace xml.sz.luohuedu.net.aspxwebcs { /// <summary> /// upload 的摘要说明。 /// </summary> [webservice(namespace="http://xml.sz.luohuedu.net/", description="在web services里利用.net框架进上载文件。")] public class upload : system.web.services.webservice { public upload() { //codegen:该调用是 asp.net web 服务设计器所必需的 initializecomponent(); } #region component designer generated code //web 服务设计器所必需的 private icontainer components = null; /// <summary> /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// </summary> private void initializecomponent() { } /// <summary> /// 清理所有正在使用的资源。 /// </summary> protected override void dispose( bool disposing ) { if(disposing && components != null) { components.dispose(); } base.dispose(disposing); } #endregion [webmethod(description="web 服务提供的方法,返回是否文件上载成功与否。")] public string uploadfile(byte[] fs,string filename) { try { ///定义并实例化一个内存流,以存放提交上来的字节数组。 memorystream m = new memorystream(fs); ///定义实际文件对象,保存上载的文件。 filestream f = new filestream(server.mappath(".") + "\\" + filename, filemode.create); ///把内内存里的数据写入物理文件 m.writeto(f); m.close(); f.close(); f = null; m = null; return "文件已经上传成功。"; } catch(exception ex) { return ex.message; } } } }

要上载文件,必须提供一个表单,来供用户进行文件的选择,下面我们就建立这样一个页面upload.aspx,用来提供文件上载:

<%@ page language="c#" codebehind="upload.aspx.cs" autoeventwireup="false" inherits="aspxwebcs.upload" %> <!doctype html public "-//w3c//dtd html 4.0 transitional//en"> <html> <head> <title>通过web services上载文件</title> <meta name="generator" content="microsoft visual studio .net 7.0"> <meta name="code_language" content="visual basic 7.0"> <meta name="vs_defaultclientscript" content="javascript"> <meta name="vs_targetschema" content="http://schemas.microsoft.com/intellisense/ie5"> </head> <body ms_positioning="gridlayout"> <form id="form1" method="post" runat="server" enctype="multipart/form-data"> <input id="myfile" type="file" runat="server"> <br> <br></p> <div class="clear-both"></div> </div> <div class="pages"><a href=20050818011043201.htm target="_self" >首页</a> <a href=20050818011043201_2.htm target="_self">下页</a> <a href=20050818011043201_2.htm target="_self">尾页</a> <a href=20050818011043201.htm target="_self"><strong>[1]</strong></a> <a href=20050818011043201_2.htm target="_self">[2]</a> </div> <div class="keywords"> <strong>本文关键:</strong>Web Service上传下载文件 </div> <div class="ad_doc_ad_2"> <script type="text/javascript"><!-- google_ad_client = "pub-1022332794981269"; google_ad_width = 728; google_ad_height = 90; google_ad_format = "728x90_as"; google_ad_type = "text_image"; //2007-03-23: 方案站728x90 google_ad_channel = "2351411502"; google_color_border = "FFFFFF"; google_color_bg = "FFFFFF"; google_color_link = "3D81EE"; google_color_text = "4C4C4C"; google_color_url = "6C82B5"; //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> </div> <div class="clear-both"></div> </div> </div> <div id="content_right"> <div class="cbox" id="relate_doc"> <div class="darkboxTitle"><span>  相关方案</span></div> <div class="ad_site_index_right_1"> <!-- SiteSearch Google --> <form method="get" action="http://www.google.cn/custom" target="google_window"> <table border="0" bgcolor="#ffffff"> <tr><td nowrap="nowrap" valign="top" align="left" height="32"> <a href="http://www.google.com/"> <img src="http://www.google.com/logos/Logo_25wht.gif" border="0" alt="Google" align="middle"></img></a> <br/> <input type="hidden" name="domains" value="www.cn-doc.com"></input> <label for="sbi" style="display: none">输入您的搜索字词</label> <input type="text" name="q" size="15" maxlength="255" value="" id="sbi"></input> <label for="sbb" style="display: none">提交搜索表单</label> <input type="submit" name="sa" value="搜索" id="sbb"></input> </td></tr> <tr> <td nowrap="nowrap"> <table> <tr> <td> <input type="radio" name="sitesearch" value="" id="ss0"></input> <label for="ss0" title="搜索网络"><font size="-1" color="#000000">Web</font></label></td> <td> <input type="radio" name="sitesearch" value="www.cn-doc.com" checked id="ss1"></input> <label for="ss1" title="搜索 www.cn-doc.com"><font size="-1" color="#000000">www.cn-doc.com</font></label></td> </tr> </table> <input type="hidden" name="client" value="pub-1022332794981269"></input> <input type="hidden" name="forid" value="1"></input> <input type="hidden" name="channel" value="9722277709"></input> <input type="hidden" name="ie" value="GB2312"></input> <input type="hidden" name="oe" value="GB2312"></input> <input type="hidden" name="flav" value="0000"></input> <input type="hidden" name="sig" value="Dl1iwOxBnXTtaDIa"></input> <input type="hidden" name="cof" value="GALT:#008000;GL:1;DIV:#336699;VLC:663399;AH:center;BGC:FFFFFF;LBGC:336699;ALC:0000FF;LC:0000FF;T:000000;GFNT:0000FF;GIMP:0000FF;LH:50;LW:200;L:http://www.cn-doc.com/images/forgoogle.gif;S:http://www.cn-doc.com;FORID:1"></input> <input type="hidden" name="hl" value="zh-CN"></input> </td></tr></table> </form> <!-- SiteSearch Google --> </div> <ul class="darklist"> <li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011043215.htm" title="建网站十大误区" target="_blank">建网站十大误区</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011043233.htm" title="Asp无组件上传进度条解决方案" target="_blank">Asp无组件上传进度条解决方案</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011043431.htm" title="动态生成Flash网页" target="_blank">动态生成Flash网页</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011043275.htm" title="javascript实现语法分色编辑器...(同时支持动态读取对象方法)" target="_blank">javascript实现语法分</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011043417.htm" title="IE浏览器不能打开新窗口的解决办法" target="_blank">IE浏览器不能打开新窗口的解决</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011043772.htm" title="Stream media html code" target="_blank">Stream media ht</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011044841.htm" title="用XMLHTTP Post/Get HTML页面时的中文乱码问题之完全Script解决方案" target="_blank">用XMLHTTP Post/G</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011044218.htm" title="文字性质的CSS" target="_blank">文字性质的CSS</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/2005081801104482.htm" title="在Web页上模拟(QQ)魔法表情" target="_blank">在Web页上模拟(QQ)魔法表</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011044447.htm" title="Url Rewrite" target="_blank">Url Rewrite</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011043826.htm" title="以一个最简单的例子把OO的JavaScript说明白" target="_blank">以一个最简单的例子把OO的Ja</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011043381.htm" title="从页面结构推荐全Flash页" target="_blank">从页面结构推荐全Flash页</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011043451.htm" title="客户端实现类似于DataGrid的输入表格控件" target="_blank">客户端实现类似于DataGri</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011042216.htm" title="Squid做反向加速,配合DNS轮询实现简单负载均衡典型配置" target="_blank">Squid做反向加速,配合DN</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011042113.htm" title="改善javascript性能的几个技巧" target="_blank">改善javascript性能的</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/2005081801104256.htm" title="去除51.net免费空间广告的方法" target="_blank">去除51.net免费空间广告的</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011042796.htm" title="BBS2Blog-让BBS与Weblog互通" target="_blank">BBS2Blog-让BBS与W</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011042698.htm" title="什么是RSS?" target="_blank">什么是RSS?</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011042356.htm" title="为何不能交互式登陆?" target="_blank">为何不能交互式登陆?</a>…</li><li><a href="../../_soft_web_tech_doc/2005_08_18_01/20050818011042321.htm" title="用JS刚完成的即时战略模型" target="_blank">用JS刚完成的即时战略模型</a>…</li> </ul> <div class="ad_site_index_right_2"> <script type="text/javascript"><!-- google_ad_client = "pub-1022332794981269"; google_ad_width = 180; google_ad_height = 60; google_ad_format = "180x60_as_rimg"; google_cpa_choice = "CAAQ0cX8zwEaCEpGRZ0Cl8yyKPu_93M"; google_ad_channel = "6903800490"; //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> </div> </div> </div> <div class="clear-both">&nbsp;</div> <div id="ContentBottom" class="darkBox"> <p>本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)</p><a href="#"><img src="../../images/btn_top.gif" width="51" height="11" alt="go top"/></a> </div> </div> </div> <script type="text/javascript" language="javascript" src="../../comm/doc/w3c_99_bottom.js"></script> <script type="text/javascript" language="javascript" src="../../comm/clicksum_doc.asp?typeid=50&infoid=370829"></script> <script type="text/javascript" language="JavaScript" src="../../comm/statistics.js"></script> </body> </html>