通过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.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 aspxWebCS
{
/// <summary>
/// Upload 的摘要说明。
/// 利用该方法通过Web Services上载文件
/// </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);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </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)
{
///首先得到上载文件信息和文件流
if(MyFile.PostedFile != null)
{
System.Web.HttpFileCollection oFiles;
oFiles = System.Web.HttpContext.Current.Request.Files;
if(oFiles.Count < 1)
{
Response.Write ("请选择文件。");
Response.End();
}

string FilePath = oFiles[0].FileName;
if(FilePath == "" || FilePath == null)
{
Response.Write ("请选择一个文件。");
Response.End();
}
string FileName = FilePath.Substring(FilePath.LastIndexOf("//")+1);
try
{
///处理上载的文件流信息。
byte[] b = new byte[oFiles[0].ContentLength];
System.IO.Stream fs;
xml.sz.luohuedu.net.aspxWebCS.Upload o;
o = new xml.sz.luohuedu.net.aspxWebCS.Upload();
fs = (System.IO.Stream)oFiles[0].InputStream;
fs.Read(b, 0, oFiles[0].ContentLength);
///调用Web Services的UploadFile方法进行上载文件。
Response.Write(o.UploadFile(b, FileName));
fs.Close();
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
else
{
Response.Write("请选择文件");
}
}
}
}

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

<configuration>
<system.web>
<httpRuntime maxRequestLength="1048576" executionTimeout="3600" />
</system.web>
</configuration>

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

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

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

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

<configuration>
<system.web>
<processModel memoryLimit="80"/>
</system.web>
</configuration>

我在自己的机器上测试,可以上传50M以上的文件。以上代码在Windows XP + .NET 1.0 + VS.NET2002下测试通过。 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值