首页 ┆ 网站地图 ┆ 在线留言 ┆ 游戏资讯 ┆ 资源下载 ┆ 端午节祝福 ┆ 迅雷在线影视 ┆淘宝手机在线充值 ┆淘宝游戏点卡充值 
设为首页
加入收藏
联系我们
高级搜索
您当前的位置: 主页>NET专区>SERVICES>通过Web Services上传和下载文件的实例
通过Web Services上传和下载文件的实例
来源: 发布时间:2007-09-05 发布人: 浏览: 人次   字体: [ ]  

随着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>
<center> <br /> 共2页: 上一页 1 <a href='94_2.html'>[2]</a> <a href='94_2.html'>下一页</a> </center></td></tr></table></td></tr><!--网页推荐开始--> <TR><TD align="center"><div class="artool"> 【<a href="#top" title="返回本页面的顶部">↑返回顶部</a>】 【<a href="/plus/feedback.php?arcID=94" title="对本文章发表您的看法" target="_blank">文章评论(0条)</a>】 【<a href="javascript:window.external.addFavorite('http://www.itwis.com/plus/view.php?aid=94','通过Web Services上传和下载文件的实例--IT知道网')" title="收藏本文章" target="_self">收藏本文</a>】 【<a href="javascript:window.print();" title="打印当前文章" target="_self">打印本文</a>】 【<a href="#" title='关闭当前窗口' onClick="window.close();">关闭窗口↓</a>】 </div> </TD> </tr> <!--网页推荐结束--> <tr> <td height="26" colspan="2" align="left" valign="middle" style="border-top:1px solid #cccccc"> <div style="text-align: left">↑上一篇:没有了 </div> <div style="text-align: left">↓下一篇:<a href='/html/net/webservices/20070905/95.html'>如何创建和使用Web服务</a> </div> </td> </tr> <!--相关文章开始--> <tr><td valign="top" colspan="2"> <table width="100%" border="0" cellpadding="1" cellspacing="1"> <tr> <td width="49%" align="center" bgcolor="#FE850C">相 关 文 章</td> <td width="2%" rowspan="2">&nbsp;</td> <td width="49%" align="center" bgcolor="#FE850C">发布商链接</td> </tr><tr><td> <table width="100%" border="0" cellspacing="0" cellpadding="0"><tr> <td valign="top" class="showlist1">·<a href='/html/net/webservices/20070905/95.html' title ="如何创建和使用Web服务" target="_blank">如何创建和使用Web服务</a><br></td></tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20071110/516.html' title ="小解ASP.NET AJAX中的异步Web Services调用实例" target="_blank">小解ASP.NET AJAX中的异步Web Servic...</a><br></td></tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20080409/1228.html' title ="如何使用WebServices调用存储过程代码实例" target="_blank">如何使用WebServices调用存储过程代...</a><br></td></tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20080410/1254.html' title ="如何实现不用编写客户端也能调试WebServices?" target="_blank">如何实现不用编写客户端也能调试WebS...</a><br></td></tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20080508/1455.html' title ="webservice在远程不能被调用解决方案" target="_blank">webservice在远程不能被调用解决方案</a><br></td></tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20080708/1949.html' title ="取消一个正在进行中的Web Service" target="_blank">取消一个正在进行中的Web Service</a><br></td></tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20080801/2109.html' title ="哪些情况可以使用Web service,哪些情况不可以?" target="_blank">哪些情况可以使用Web service,哪些...</a><br></td></tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20080829/2293.html' title ="如何实现在asp.net中实现WebServices下载和上传文件" target="_blank">如何实现在asp.net中实现WebServices...</a><br></td></tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20081129/2977.html' title ="探讨Web Service什么时候该用,什么时候不推荐用" target="_blank">探讨Web Service什么时候该用,什么...</a><br></td></tr> <td colspan="2" valign="top" class="showlist1"> </td></table></td> <td valign="top"><script language='JavaScript' type='text/JavaScript' src='/js/am.js'></script></td> </tr> </table></td> </tr> <!--相关文章结束--> <!--评论开始--> <tr><td colspan="2" valign="top" bgcolor="#FAFEF1"> <table width="198%" border="0" cellpadding="1" cellspacing="1" bgcolor="#C5CDBE" ><tr> <td height="23" bgcolor="#F0F8D8">&nbsp;§<a href="/plus/feedback.php?arcID=94" target="_blank" title="查看对本文章的最新评论"><u>最新评论</u></a>:(评论内容只代表网友观点,与本站立场无关!)</td></tr><tr><td bgcolor="#FFFFFF"> <script src="/plus/feedback_js.php?arcID=94" language="javascript"></script></td> </tr></table></td></tr><tr valign="top"> <td height="26" colspan="2" align="center" style="border-top:1px solid #cccccc"> <table width="100%" border="0" cellpadding="1" cellspacing="1"> <form action="/plus/feedback.php?action=send" method="post" name="feedback"> <input type="hidden" name="arcID" value="94"><tr> <td>网名: <input name="username" type="text" id="username" size="10" class="nb">验证码: <input name="vdcode" type="text" id="vdcode" style="width:80;height:20"> <img src='/plus/../include/validateimg.php' width='50' height='20'> <input type='submit' value='发表评论' name='sb' onClick='return FormVali()' style='width:60;height:20' class="button2"> &nbsp;【<a href="/plus/feedback.php?arcID=94" target="_blank">所有评论</a>】【<a href="#top" title="返回顶部">↑返回顶部</a>】</td></tr><tr><td bgcolor="#FFFFFF">评 分: <input type="radio" name="rank" value="1">1<input type="radio" name="rank" value="2">2<input name="rank" type="radio" value="3"> 3<input type="radio" name="rank" value="4">4<input type="radio" name="rank" value="5">5</td></tr><tr> <td>评论内容:(不能超过500字,请自觉遵守互联网相关政策法规。<font color="#FF0000">[按 Ctrl+Enter 可直接提交]</font></td> </tr><tr><td><textarea name="msg" cols="75" rows="4" id="msg" style="width:98%"></textarea></td></tr></form></table></td></tr><!--评论结束--> <tr valign="top"><td colspan="2"><font color="#FF0000">注意:</font>请勿在本站发布政治话题、色情及违反法律的内容。</td></tr> <tr><TD align="center" valign="top"><div align="left"><a href="http://www.itwis.com" target="_blank">IT知道网</a> <span style="color:#0000FF">声明:刊登此文章是为了传递更多信息,文章内容仅供参考,转载请注明出处。</span></div></TD></TR></table></div><script language='JavaScript' type='text/JavaScript' src='/js/qs.js'></script><script language='javascript' type='text/JavaScript' src='/js/bq.js'></script></td> <td width="228" > <table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td> <script language='JavaScript' type='text/JavaScript' src='/js/ra.js'></script> </td></tr></table> <table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td class="titleback1">推 荐 文 章</td></tr> <tr> <td valign="top" class="showlist1">·<a href='/html/net/webservices/20080508/1455.html' title ="webservice在远程不能被调用解决方案" target="_blank">webservice在远程不能被调用...</a></td> </tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20080410/1254.html' title ="如何实现不用编写客户端也能调试WebServices?" target="_blank">如何实现不用编写客户端也能...</a></td> </tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20080409/1228.html' title ="如何使用WebServices调用存储过程代码实例" target="_blank">如何使用WebServices调用存储</a></td> </tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20071110/516.html' title ="小解ASP.NET AJAX中的异步Web Services调用实例" target="_blank">小解ASP.NET AJAX中的异步Web...</a></td> </tr> <td colspan="2" valign="top" class="showlist1"> </td></table> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr><td class="titleback1">热 门 文 章</td></tr><tr> <td valign="top" class="showlist1">·<a href='/html/net/webservices/20080410/1254.html' title ="如何实现不用编写客户端也能调试WebServices?" target="_blank">如何实现不用编写客户端也能...</a></td> </tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20071110/516.html' title ="小解ASP.NET AJAX中的异步Web Services调用实例" target="_blank">小解ASP.NET AJAX中的异步Web...</a></td> </tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20080508/1455.html' title ="webservice在远程不能被调用解决方案" target="_blank">webservice在远程不能被调用...</a></td> </tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20080801/2109.html' title ="哪些情况可以使用Web service,哪些情况不可以?" target="_blank">哪些情况可以使用Web service...</a></td> </tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20080829/2293.html' title ="如何实现在asp.net中实现WebServices下载和上传文件" target="_blank">如何实现在asp.net中实现WebS...</a></td> </tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20070905/95.html' title ="如何创建和使用Web服务" target="_blank">如何创建和使用Web服务</a></td> </tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20080409/1228.html' title ="如何使用WebServices调用存储过程代码实例" target="_blank">如何使用WebServices调用存储...</a></td> </tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20080708/1949.html' title ="取消一个正在进行中的Web Service" target="_blank">取消一个正在进行中的Web Ser...</a></td> </tr> <td colspan="2" valign="top" class="showlist1"> ·<a href='/html/net/webservices/20081129/2977.html' title ="探讨Web Service什么时候该用,什么时候不推荐用" target="_blank">探讨Web Service什么时候该用...</a></td> </tr> <td colspan="2" valign="top" class="showlist1"> </td> </table> <!--Google提供的广告开始--> <table width="100%" border="0"> <tr> <td valign="top" align="center"> <script type="text/javascript"><!-- google_ad_client = "pub-2332246972783672"; /* 160x600, 创建于 08-4-8 */ google_ad_slot = "9894726136"; google_ad_width = 160; google_ad_height = 600; //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> </td> </tr> </table> <!--Google提供的广告结束--> </td></tr></table> <!-- 页面底部开始 --> <center><link href="/plus/cun/cun.css" rel="stylesheet" type="text/css"> <table width="900" border="0" align="center" cellpadding="0" cellspacing="0" class="tableborder"> <tr> <td height="5"></td> </tr> <tr> <td height="8" class="linebar"></td> </tr> <tr> <td height="5"></td> </tr> <tr> <td height="65" align="center" class="tablebody"> <a href="http://www.itwis.com" title="IT知道网主页" class="navmenu">网站首页</a> - <a href="http://www.itwis.com/about.htm" title="关于本站的介绍" target="_blank" class="navmenu">关于本站</a> - <a href="javascript:window.external.AddFavorite('http://www.itwis.com','IT知道网')" title="将本站加入到你的收藏夹" class="navmenu">加入收藏</a> - <a href="/plus/sitemap.html" target="_blank" class="navmenu" title="网站地图">网站地图</a> - <a href="/plus/flink.php" target="_blank" class="navmenu" title="友情连接">友情连接</a> - <a href="/plus/guestbook/index.php" target="_blank" class="navmenu" title="给我们留言,互相交流">在线留言</a> - <a href="mailto:itwis@163.com" title="给我们写信" class="navmenu">联系我们</a> - <a href="#top" title="返回本页面顶部" class="navmenu">返回顶部</a><br> Copyright &copy; 2007 <a href="http://www.itwis.com" target="_blank" class="navmenu"><strong>IT知道网</strong></a>.<a href="http://www.miibeian.gov.cn" target="_blank" class="navmenu">[冀ICP备07026896号]</a>. All Rights Reserved .<br /> <script src='http://s62.cnzz.com/stat.php?id=610829&web_id=610829' language='JavaScript' charset='gb2312'></script></td> </tr> <tr> <td height="5"></td> </tr> </table> </center> </body> </html> <!-- 页面底部结束 -->