技术积累

明日复明日,明日何其多,我生待明日,万事成蹉跎。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

通过Web Services显示和下载文件

Posted on 2005-09-28 16:50  追风逐云.NET  阅读(1642)  评论(0编辑  收藏  举报

随着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> <asp:Button id="Button1" runat="server" Text="上载文件"></asp:Button> </form> </body> </html>

我们要进行处理的是在后代码里面,下面详细的介绍,Upload.aspx.cs:

using System; using System.Collections; using System.Componen</span> </td> </tr> <tr> <td> <div><span class="unnamed3"><table bgcolor=#FFFFFF><form action=/html/12/41340.htm method=post name=REG><tr><td><br><input type=hidden name=act value=Reg><input type="hidden" name="regid" value="3f407be54cbb162d83ba3b2b57b5443a"><fieldset class="Text2"><legend><b>验证码确认</b></legend><table cellspacing=0><tr><td width=1%>确认验证码<div class=Text2>请输入图片上的 6 位数字.</div><input type=text size=25 maxlength=32 name=reg_code></td><td align=center><img src="http://www.zahui.com/show_image.php?rc=3f407be54cbb162d83ba3b2b57b5443a"></td></tr></table></td></tr><tr><td><input type=submit value="提交验证查看全部文章"></td></tr></form></table></span></div> </td> </tr> </table> <table width="100%" border="0" cellpadding="9" cellspacing="0" align="center" bgcolor="#FFFFFF"> <tr> <td><span class="unnamed2"><table><tr><td><fieldset class="Text2"><legend><b>相关文章</b></legend><a href= http://www.zahui.com/html/9/41330.htm>应用服务器的技术发展趋势</a><br><a href= http://www.zahui.com/html/9/41331.htm>在Smartphone/Pocket PC 2003上设置提醒</a><br><a href= http://www.zahui.com/html/9/41332.htm>关联控制服务元素(ISO ACSE)--网络大典</a><br><a href= http://www.zahui.com/html/9/41333.htm>管理工作中的50点感悟</a><br><a href= http://www.zahui.com/html/9/41334.htm>来自ISBSG的标杆数据(分享)</a><br><a href= http://www.zahui.com/html/9/41335.htm>2 VNCServer Scripts Compare[Merge by MS Word]</a><br><a href= http://www.zahui.com/html/9/41336.htm>英语(1)备考——翻译</a><br><a href= http://www.zahui.com/html/9/41337.htm>Azureus 2.2.0.3 beta 9</a><br><a href= http://www.zahui.com/html/9/41338.htm>马化腾:一个空手套高手 曾经差点卖掉QQ</a><br><a href= http://www.zahui.com/html/9/41339.htm>大型网站的Google排名策略</a><br><a href= http://www.zahui.com/html/12/41341.htm>IE问题解决方法汇总!</a><br><a href= http://www.zahui.com/html/12/41342.htm>checkbox的全选、全不选</a><br><a href= http://www.zahui.com/html/13/41343.htm>RSA被山东大学破解!!?</a><br><a href= http://www.zahui.com/html/13/41344.htm>创业者的十大“必杀技”</a><br><a href= http://www.zahui.com/html/13/41345.htm>昨日关注:从企业的运行价值链说起——我眼中的测试驱动开发(TDD)</a><br><a href= http://www.zahui.com/html/13/41346.htm>如何奔向程序员打工的出头之日?</a><br><a href= http://www.zahui.com/html/13/41347.htm>mrxsmb System 8003 Error</a><br><a href= http://www.zahui.com/html/13/41348.htm>ADSL512下使bt下载达到理想速度</a><br><a href= http://www.zahui.com/html/13/41349.htm>FreeBSD 下的TOP的使用方法</a><br><a href= http://www.zahui.com/html/13/41350.htm>深入浅出基于Java的解释器设计模式</a><br></td></tr></table> </span></td> </tr> <tr> <td> <span class="unnamed2"> <table><tr><td><fieldset class="Text2"><legend><b>所有分类</b></legend><a href= http://www.zahui.com/html/1/>Visual C++</a><br><a href= http://www.zahui.com/html/2/>Delphi</a><br><a href= http://www.zahui.com/html/3/>Visual Basic</a><br><a href= http://www.zahui.com/html/4/>ASP</a><br><a href= http://www.zahui.com/html/5/>Perl</a><br><a href= http://www.zahui.com/html/6/>Java</a><br><a href= http://www.zahui.com/html/7/>Javascript</a><br><a href= http://www.zahui.com/html/8/>数据库开发</a><br><a href= http://www.zahui.com/html/9/>其他开发语言</a><br><a href= http://www.zahui.com/html/10/>游戏开发</a><br><a href= http://www.zahui.com/html/11/>文件格式</a><br><a href= http://www.zahui.com/html/12/>网站制作技术</a><br><a href= http://www.zahui.com/html/13/>其他</a><br><a href= http://www.zahui.com/html/14/>.NET</a><br></td></tr></table> <br> <table><tr><td><fieldset class="Text2"><legend><b>相关网站</b></legend><a href="http://www.zahui.com/">技术大杂烩 </a><br><a href="http://linuxsir.zahui.net/">linuxsir技术文档</a><br><a href="http://freebsdforums.zahui.net/">freebsdforums技术文档</a><br><a href="http://51js.zahui.net/">51js技术文档</a><br><a href="http://cnoug.zahui.net/">cnoug技术文档</a></td></tr></table> </span> </td> </tr> </table> <div align="center"> <script language=JavaScript src="../../foot.js"></script> </div> <table width="100%" border="0" cellpadding="3" cellspacing="0" bgcolor="#FFFFFF" align="center"> <tr align="center" bgcolor="#006633"> <td height="27"> <span><font color="#FFFFFF">合作事项</font> <font color="#FFFFFF">| 业务联系</font> <font color="#FFFFFF">|</font> <font color="#FFFFFF">广告刊登</font> <font color="#FFFFFF">|</font> <a href=http://www.zhaocount.com><font color="#FFFFFF">计数器</font></a> <font color="#FFFFFF">|</font> <a href="javascript:window.external.AddFavorite('http://www.ZaHui.com/','技术大杂烩')"><font color="#FFFFFF">加入收藏</font></a></span></td> </tr> <tr bgcolor="#F6F6F6" align="center" valign="bottom"> <td height="29">[ <a href="http://www.zahui.com">www.ZaHui.com</a> ]  </td> </tr> <tr bgcolor="#F6F6F6" align="center"> <td height="29">Copyright © 2000-2004 <a href="http://www.zahui.com">www.ZaHui.com</a> All rights reserved </td> </tr> </table> </td> </tr> </tbody> </table> </td> <td valign=top align=left width=10 background="../../images/bg_right.gif" height="231"><img src="../../images/blank.gif" width="8" height="1"></td> </tr> </tbody> </table> <script>var a="zahui";</script> <script src="http://www.zahui.com/stat.js"></script> </body> </html>