首页 > 开发 > .Net > 正文

asp.net Web Services上传和下载文件(完整代码)第1/2页

2020-04-24 22:04:10
字体:
来源:转载
供稿:网友
下面,我们就分别介绍如何通过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:
代码如下:
usingSystem;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Diagnostics;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.Services;
usingSystem.IO;
namespacexml.sz.luohuedu.net.aspxWebCS
{
///<summary>
///GetBinaryFile的摘要说明。
///WebServices名称:GetBinaryFile
///功能:返回服务器上的一个文件对象的二进制字节数组。
///</summary>
[WebService(Namespace="http://xml.sz.luohuedu.net/",
Description="在WebServices里利用.NET框架进行传递二进制文件。")]
publicclassGetBinaryFile:System.Web.Services.WebService
{
#regionComponentDesignergeneratedcode
//Web服务设计器所必需的
privateIContainercomponents=null;
///<summary>
///清理所有正在使用的资源。
///</summary>
protectedoverridevoidDispose(booldisposing)
{
if(disposing&&components!=null)
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
publicclassImages:System.Web.Services.WebService
{
///<summary>
///Web服务提供的方法,返回给定文件的字节数组。
///</summary>
[WebMethod(Description="Web服务提供的方法,返回给定文件的字节数组")]
publicbyte[]GetImage(stringrequestFileName)
{
///得到服务器端的一个图片
///如果你自己测试,注意修改下面的实际物理路径
if(requestFileName==null||requestFileName=="")
returngetBinaryFile("D://Picture.JPG");
else
returngetBinaryFile("D://"+requestFileName);
}
///<summary>
///getBinaryFile:返回所给文件路径的字节数组。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表