通过webservices上传下载文件

flashicp 整理

最近在用webservices的东西所以就整理了这些文件供大家参考

一:通过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.

1<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank">asp</a>

xWebCS
{
///

1<summary>   
2/// GetBinaryFile 的摘要说明。   
3/// Web Services名称:GetBinaryFile   
4/// 功能:返回<a href=" http://www.chinaitpower.com/System/Server/index.html " target="_blank">服务器</a>上的一个<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>对象的二进制字节数组。   
5/// </summary>

[WebService(Namespace=" http://xml.sz.luohuedu.net/ ",
Description="在Web Services里利用.NET框架进行传递二进制

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

。")]
public class GetBinaryFile : System.Web.Services.WebService
{

#region Component Designer generated code
//Web 服务设计器所必需的
private IContainer components = null;

///

1<summary>   
2/// 清理所有正在使用的资源。   
3/// </summary>

protected override void Dispose( bool disposing )
{
if(disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}

#endregion

public class Images: System.Web.Services.WebService
{
///

1<summary>   
2/// Web 服务提供的方法,返回给定<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>的字节数组。   
3/// </summary>

[WebMethod(Description="Web 服务提供的方法,返回给定

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

的字节数组")]
public byte[] GetImage(string requestFileName)
{
///得到

1<a href=" http://www.chinaitpower.com/System/Server/index.html " target="_blank">服务器</a>

端的一个图片
///如果你自己测试,注意修改下面的实际物理路径
if(requestFileName == null || requestFileName == "")
return getBinaryFile("D:\\Picture.JPG");
else
return getBinaryFile("D:\" + requestFileName);
}

///

1<summary>   
2/// getBinaryFile:返回所给<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>路径的字节数组。   
3/// </summary>

///

1<param name="filename"/>

///

1<returns></returns>

public byte[] getBinaryFile(string filename)
{
if(File.Exists(filename))
{
try
{
///打开现有

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

以进行读取。
FileStream s = File.OpenRead(filename);
return ConvertStreamToByteBuffer(s);
}
catch(Exception e)
{
return new byte[0];
}
}
else
{
return new byte[0];
}
}
///

1<summary>   
2/// ConvertStreamToByteBuffer:把给定的<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>流转换为二进制字节数组。   
3/// </summary>

///

1<param name="theStream"/>

///

1<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 服务提供的方法,返回给定

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

类型。")]
public string GetImageType()
{
///这里只是测试,您可以根据实际的

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

类型进行动态输出
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

1<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank">asp</a>

xWebCS
{
///

1<summary>   
2/// GetBinaryFileShow 的摘要说明。   
3/// </summary>

public class GetBinaryFileShow : System.Web.UI.Page
{

private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
///定义并初始化

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

对象;
xml.sz.luohuedu.net.

1<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank">asp</a>

xWebCS.GetBinaryFile.Images oImage;
oImage = new xml.sz.luohuedu.net.

1<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank">asp</a>

xWebCS.GetBinaryFile.Images();
///得到二进制

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

字节数组;
byte[] image = oImage.GetImage("");
///转换为支持存储区为内存的流
System.IO.MemoryStream memStream = new System.IO.MemoryStream(image);
///定义并实例化Bitmap对象
Bitmap bm = new Bitmap(memStream);
///根据不同的条件进行输出或者下载;
Response.Clear();
///如果请求

1<a href=" http://www.chinaitpower.com/Dev/Programme/VC/Str/index.html " target="_blank">字符</a>

串指定下载,就下载该

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>


///否则,就显示在浏览器中。
if(Request.QueryString["Download"]=="1")
{
Response.Buffer = true;
Response.ContentType = "application/octet-stream";
///这里下载输出的

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

名字 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);
}

///

1<summary>   
2/// 设计器支持所需的方法 - 不要使用代码编辑器修改   
3/// 此方法的内容。   
4/// </summary>

private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion
}
}

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

1@ Page language="c#" Codebehind="GetBinaryFile.

asp

1x.cs" AutoEventWireup="false"   
2Inherits="

asp

1xWebCS.GetBinaryFile" 
 1<html>
 2<head>
 3<title>通过Web Services显示和下载<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a></title>
 4<meta content="Microsoft Visual Studio 7.0" name="GENERATOR"/>
 5<meta content="C#" name="CODE_LANGUAGE"/>
 6<meta content="JavaScript" name="vs_defaultClientScript"/>
 7<meta content=" http://schemas.microsoft.com/intellisense/ie5 " name="vs_targetSchema"/>
 8</head>
 9<body ms_positioning="GridLayout">
10<form id="GetBinaryFile" method="post" runat="server">
11<font face="宋体">   
12&lt;<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank">asp</a>:HyperLink id="HyperLink1" NavigateUrl="GetBinaryFileShow.<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank">asp</a>x?Download=1"   
13runat="server"&gt;下载<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a><!--<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank"-->asp:HyperLink&gt;   
14
15   
16<!--下面是直接显示<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>\-->   
17&lt;<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank">asp</a>:Image id="Image1" ImageUrl="GetBinaryFileShow.<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank">asp</a>x" runat="server"&gt;<!--<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank"-->asp:Image&gt;   
18</font>
19</form>
20</body>
21</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.

1<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank">asp</a>

xWebCS
{
///

1<summary>   
2/// Upload 的摘要说明。   
3/// </summary>

[WebService(Namespace=" http://xml.sz.luohuedu.net/ ",
Description="在Web Services里利用.NET框架进上载

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

。")]
public class Upload : System.Web.Services.WebService
{
public Upload()
{
//CODEGEN:该调用是 ASP.NET Web 服务设计器所必需的
InitializeComponent();
}

#region Component Designer generated code

//Web 服务设计器所必需的
private IContainer components = null;

///

1<summary>   
2/// 设计器支持所需的方法 - 不要使用代码编辑器修改   
3/// 此方法的内容。   
4/// </summary>

private void InitializeComponent()
{
}

///

1<summary>   
2/// 清理所有正在使用的资源。   
3/// </summary>

protected override void Dispose( bool disposing )
{
if(disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}

#endregion

[WebMethod(Description="Web 服务提供的方法,返回是否

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

上载成功与否。")]
public string UploadFile(byte[] fs,string FileName)
{
try
{
///定义并实例化一个内存流,以存放提交上来的字节数组。
MemoryStream m = new MemoryStream(fs);
///定义实际

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

对象,保存上载的

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>


FileStream f = new FileStream(Server.MapPath(".") + "\"
+ FileName, FileMode.Create);
///把内内存里的数据写入物理

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

m.WriteTo(f);
m.Close();
f.Close();
f = null;
m = null;
return "

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

已经上传成功。";
}
catch(Exception ex)
{
return ex.Message;
}
}
}
}

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

1@ Page language="c#" Codebehind="Upload.

asp

1x.cs" AutoEventWireup="false"   
2Inherits="

asp

1xWebCS.Upload" 
 1<html>
 2<head>
 3<title>通过Web Services上载<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a></title>
 4<meta content="Microsoft Visual Studio .NET 7.0" name="GENERATOR"/>
 5<meta content="Visual Basic 7.0" name="CODE_LANGUAGE"/>
 6<meta content="JavaScript" name="vs_defaultClientScript"/>
 7<meta content=" http://schemas.microsoft.com/intellisense/ie5 " name="vs_targetSchema"/>
 8</head>
 9<body ms_positioning="GridLayout">
10<form enctype="multipart/form-data" id="Form1" method="post" runat="server">
11<input id="MyFile" runat="server" type="file"/>
12<br/>
13<br/>   
14&lt;<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank">asp</a>:Button id="Button1" runat="server" Text="上载<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>"&gt;<!--<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank"-->asp:Button&gt;   
15</form>
16</body>
17</html>

我们要进行处理的是在后代码里面,下面详细的介绍,Upload.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;
using System.IO;

namespace

1<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank">asp</a>

xWebCS
{
///

1<summary>   
2/// Upload 的摘要说明。   
3/// 利用该方法通过Web Services上载<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>   
4/// </summary>

public class Upload : System.Web.UI.Page
{
protected System.Web.UI.HtmlControls.HtmlInputFile MyFile;
protected System.Web.UI.WebControls.Button Button1;

private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

///

1<summary>   
2/// 设计器支持所需的方法 - 不要使用代码编辑器修改   
3/// 此方法的内容。   
4/// </summary>

private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void Button1_Click(object sender, System.EventArgs e)
{
///首先得到上载

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

信息和

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>


if(MyFile.PostedFile != null)
{
System.Web.HttpFileCollection oFiles;
oFiles = System.Web.HttpContext.Current.Request.Files;
if(oFiles.Count < 1)
{
Response.Write ("请选择

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

。");
Response.End();
}

string FilePath = oFiles[0].FileName;
if(FilePath == "" || FilePath == null)
{
Response.Write ("请选择一个

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

。");
Response.End();
}
string FileName = FilePath.Substring(FilePath.LastIndexOf(" \")+1 );
try
{
///处理上载的

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

流信息。
byte[] b = new byte[oFiles[0].ContentLength];
System.IO.Stream fs;
xml.sz.luohuedu.net.

1<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank">asp</a>

xWebCS.Upload o;
o = new xml.sz.luohuedu.net.

1<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank">asp</a>

xWebCS.Upload();
fs = (System.IO.Stream)oFiles[0].InputStream;
fs.Read(b, 0, oFiles[0].ContentLength);
///调用Web Services的UploadFile方法进行上载

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>


Response.Write(o.UploadFile(b, FileName));
fs.Close();
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
else
{
Response.Write("请选择

1<a href=" http://www.chinaitpower.com/Soft/Tools/File/index.html " target="_blank">文件</a>

");
}
}
}
}

最后,需要注意的是:在保存文件时,您应该确保指定文件的完整路径(例如,"C:\MyFiles\Picture.jpg"),并确保为 ASP.NET 使用的帐户提供要存储文件的目录的写权限。上载大文件时,可使用 元素的 maxRequestLength 属性来增加文件大小的最大允许值,例如:

1<configuration>
2<system.web>
3<httpruntime executiontimeout="3600" maxrequestlength="1048576"></httpruntime>
4</system.web>
5</configuration>

其中:maxRequestLength:指示 ASP.NET 支持的HTTP方式上载的最大字节数。该限制可用于防止因用户将大量文件传递到该服务器而导致的拒绝服务攻击。指定的大小以 KB 为单位。默认值为 4096 KB (4 MB)。executionTimeout:指示在被 ASP.NET 自动关闭前,允许执行请求的最大秒数。在当文件超出指定的大小时,如果浏览器中会产生 DNS 错误或者出现服务不可得到的情况,也请修改以上的配置,把配置数加大。

另外,上载大文件时,还可能会收到以下错误信息:

1<a href=" http://www.chinaitpower.com/Dev/Web/Asp/index.html " target="_blank">asp</a>

net_wp.exe (PID: 1520) 被回收,因为内存消耗超过了 460 MB(可用 RAM 的百分之 60)。

如果遇到此错误信息,请增加应用程序的 Web.config 文件的 元素中 memoryLimit 属性的值。例如:

1<configuration>
2<system.web>
3<processmodel memorylimit="80"></processmodel>
4</system.web>
5</configuration>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus