一:通过Web Services显示和下载文件
我们这里建立的Web Services的名称为GetBinaryFile,提供两个公共方法:分别是GetImage()和GetImageType(),前者返回二进制文件字节数组,后者返回文件类型,其中,GetImage()方法有一个参数,用来在客户端选择要显示或下载的文件名字。这里我们所显示和下载的文件可以不在虚拟目录下,采用这个方法的好处是:可以根据权限对文件进行显示和下载控制,从下面的方法我们可以看出,实际的文件位置并没有在虚拟目录下,因此可以更好地对文件进行权限控制,这在对安全性有比较高的情况下特别有用。这个功能在以前的ASP程序中可以用Stream对象实现。为了方便读者进行测试,这里列出了全部的源代码,并在源代码里进行介绍和注释。
首先,建立GetBinaryFile.asmx文件:
我们可以在VS.NET里新建一个C#的aspxWebCS工程,然后“添加新项”,选择“Web服务”,并设定文件名为:GetBinaryFile.asmx,在“查看代码”中输入以下代码,即:GetBinaryFile.asmx.cs:
一旦我们创建了上面的asmx文件,进行编译后,我们就可以编写客户端的代码来进行调用这个Web Services了。
我们先“添加Web引用”,输入:http://localhost/aspxWebCS/GetBinaryFile.asmx。下面,我们编写显示文件的中间文件:GetBinaryFileShow.aspx,这里,我们只需要在后代码里编写代码即可,GetBinaryFileShow.aspx.cs文件内容如下:
-
usingSystem;
-
usingSystem.Collections;
-
usingSystem.ComponentModel;
-
usingSystem.Data;
-
usingSystem.Drawing;
-
usingSystem.Web;
-
usingSystem.Web.SessionState;
-
usingSystem.Web.UI;
-
usingSystem.Web.UI.WebControls;
-
usingSystem.Web.UI.HtmlControls;
-
usingSystem.Web.Services;
-
namespaceaspxWebCS
- {
-
-
-
-
publicclassGetBinaryFileShow:System.Web.UI.Page
- {
-
privatevoidPage_Load(objectsender,System.EventArgse)
- {
-
-
- xml.sz.luohuedu.net.aspxWebCS.GetBinaryFile.ImagesoImage;
-
oImage=newxml.sz.luohuedu.net.aspxWebCS.GetBinaryFile.Images();
-
-
byte[]image=oImage.GetImage("");
-
-
System.IO.MemoryStreammemStream=newSystem.IO.MemoryStream(image);
-
-
Bitmapbm=newBitmap(memStream);
-
- Response.Clear();
-
-
-
if(Request.QueryString["Download"]=="1")
- {
-
Response.Buffer=true;
-
Response.ContentType="application/octet-stream";
-
-
Response.AddHeader("Content-Disposition","attachment;filename=ok.jpg");
- }
-
else
- Response.ContentType=oImage.GetImageType();
- Response.BinaryWrite(image);
- Response.End();
-
}
-
#regionWebFormDesignergeneratedcode
-
overrideprotectedvoidOnInit(EventArgse)
- {
-
-
-
- InitializeComponent();
-
base.OnInit(e);
- }
-
-
-
-
-
privatevoidInitializeComponent()
- {
-
this.Load+=newSystem.EventHandler(this.Page_Load);
-
}
-
#endregion
- }
- }
最后,我们就编写最终的浏览页面:GetBinaryFile.aspx,这个文件很简单,只需要aspx文件即可,内容如下:
-
<%@Pagelanguage="c#"Codebehind="GetBinaryFile.aspx.cs"AutoEventWireup="false"
-
Inherits="aspxWebCS.GetBinaryFile"%>
-
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.0Transitional//EN">
- <HTML>
- <HEAD>
- <title>通过WebServices显示和下载文件</title>
-
<metaname="GENERATOR"Content="MicrosoftVisualStudio7.0">
-
<metaname="CODE_LANGUAGE"Content="C#">
-
<metaname="vs_defaultClientScript"content="JavaScript">
-
<metaname="vs_targetSchema"content="http://schemas.microsoft.com/intellisense/ie5">
- </HEAD>
-
<bodyMS_POSITIONING="GridLayout">
-
<formid="GetBinaryFile"method="post"runat="server">
-
<FONTface="宋体">
-
<asp:HyperLinkid="HyperLink1"NavigateUrl="GetBinaryFileShow.aspx?Download=1"
-
runat="server">下载文件</asp:HyperLink>
- <br/>
- <!--下面是直接显示文件-->
-
<asp:Imageid="Image1"ImageUrl="GetBinaryFileShow.aspx"runat="server"></asp:Image>
- </FONT>
- </form>
- </body>
- </HTML>
二:通过Web Services上载文件
向服务器上载文件可能有许多种方法,在利用Web Services上载文件的方法中,下面的这个方法应该是最简单的了。我们仍象前面的例子那样,首先建立Upload.asmx文件,其Upload.asmx.cs内容如下,里面已经做了注释:
-
usingSystem;
-
usingSystem.Collections;
-
usingSystem.ComponentModel;
-
usingSystem.Data;
-
usingSystem.Diagnostics;
-
usingSystem.Web;
-
usingSystem.Web.Services;
-
usingSystem.IO;
-
namespacexml.sz.luohuedu.net.aspxWebCS
- {
-
-
-
-
[WebService(Namespace="http://xml.sz.luohuedu.net/",
-
Description="在WebServices里利用.NET框架进上载文件。")]
-
publicclassUpload:System.Web.Services.WebService
- {
-
publicUpload()
- {
-
- InitializeComponent();
-
}
-
#regionComponentDesignergeneratedcode
-
-
privateIContainercomponents=null;
-
-
-
-
-
privatevoidInitializeComponent()
- {
- }
-
-
-
-
protectedoverridevoidDispose(booldisposing)
- {
-
if(disposing&&components!=null)
- {
- components.Dispose();
- }
-
base.Dispose(disposing);
-
}
-
#endregion
-
[WebMethod(Description="Web服务提供的方法,返回是否文件上载成功与否。")]
-
publicstringUploadFile(byte[]fs,stringFileName)
- {
-
try
- {
-
-
MemoryStreamm=newMemoryStream(fs);
-
-
FileStreamf=newFileStream(Server.MapPath(".")+"\\"
- +FileName,FileMode.Create);
-
- m.WriteTo(f);
- m.Close();
- f.Close();
-
f=null;
-
m=null;
-
return"文件已经上传成功。";
- }
-
catch(Exceptionex)
- {
-
returnex.Message;
- }
- }
- }
- }
要上载文件,必须提供一个表单,来供用户进行文件的选择,下面我们就建立这样一个页面Upload.aspx,用来提供文件上载:
-
<%@Pagelanguage="c#"Codebehind="Upload.aspx.cs"AutoEventWireup="false"
-
Inherits="aspxWebCS.Upload"%>
-
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.0Transitional//EN">
- <HTML>
- <HEAD>
- <title>通过WebServices上载文件</title>
-
<metaname="GENERATOR"content="MicrosoftVisualStudio.NET7.0">
-
<metaname="CODE_LANGUAGE"content="VisualBasic7.0">
-
<metaname="vs_defaultClientScript"content="JavaScript">
-
<metaname="vs_targetSchema"content="http://schemas.microsoft.com/intellisense/ie5">
- </HEAD>
-
<bodyMS_POSITIONING="GridLayout">
-
<formid="Form1"method="post"runat="server"enctype="multipart/form-data">
-
<INPUTid="MyFile"type="file"runat="server">
- <br>
- <br>
-
<asp:Buttonid="Button1"runat="server"Text="上载文件"></asp:Button>
- </form>
- </body>
- </HTML>
我们要进行处理的是在后代码里面,下面详细的介绍,Upload.aspx.cs:
-
usingSystem;
-
usingSystem.Collections;
-
usingSystem.ComponentModel;
-
usingSystem.Data;
-
usingSystem.Drawing;
-
usingSystem.Web;
-
usingSystem.Web.SessionState;
-
usingSystem.Web.UI;
-
usingSystem.Web.UI.WebControls;
-
usingSystem.Web.UI.HtmlControls;
-
usingSystem.Web.Services;
-
usingSystem.IO;
-
namespaceaspxWebCS
- {
-
-
-
-
-
publicclassUpload:System.Web.UI.Page
- {
-
protectedSystem.Web.UI.HtmlControls.HtmlInputFileMyFile;
-
protectedSystem.Web.UI.WebControls.ButtonButton1;
-
privatevoidPage_Load(objectsender,System.EventArgse)
- {
-
-
}
-
#regionWebFormDesignergeneratedcode
-
overrideprotectedvoidOnInit(EventArgse)
- {
-
-
-
- InitializeComponent();
-
base.OnInit(e);
- }
-
-
-
-
-
privatevoidInitializeComponent()
- {
-
this.Button1.Click+=newSystem.EventHandler(this.Button1_Click);
-
this.Load+=newSystem.EventHandler(this.Page_Load);
-
}
-
#endregion
-
privatevoidButton1_Click(objectsender,System.EventArgse)
- {
-
-
if(MyFile.PostedFile!=null)
- {
- System.Web.HttpFileCollectionoFiles;
- oFiles=System.Web.HttpContext.Current.Request.Files;
-
if(oFiles.Count<1)
- {
-
Response.Write("请选择文件。");
- Response.End();
- }
-
stringFilePath=oFiles[0].FileName;
-
if(FilePath==""||FilePath==null)
- {
-
Response.Write("请选择一个文件。");
- Response.End();
- }
-
stringFileName=FilePath.Substring(FilePath.LastIndexOf("\\")+1);
-
try
- {
-
-
byte[]b=newbyte[oFiles[0].ContentLength];
- System.IO.Streamfs;
- xml.sz.luohuedu.net.aspxWebCS.Uploado;
-
o=newxml.sz.luohuedu.net.aspxWebCS.Upload();
- fs=(System.IO.Stream)oFiles[0].InputStream;
- fs.Read(b,0,oFiles[0].ContentLength);
-
- Response.Write(o.UploadFile(b,FileName));
- fs.Close();
- }
-
catch(Exceptionex)
- {
- Response.Write(ex.Message);
- }
- }
-
else
- {
-
Response.Write("请选择文件");
- }
- }
- }
- }
最后,需要注意的是:在保存文件时,您应该确保指定文件的完整路径(例如,"C:\MyFiles\Picture.jpg"),并确保为 ASP.NET 使用的帐户提供要存储文件的目录的写权限。上载大文件时,可使用 <httpruntime>元素的 maxRequestLength 属性来增加文件大小的最大允许值,例如:</httpruntime>
<xmp><configuration><system.web><httpruntime maxrequestlength="1048576" executiontimeout="3600"></httpruntime></system.web></configuration></xmp>其中:maxRequestLength:指示 ASP.NET 支持的HTTP方式上载的最大字节数。该限制可用于防止因用户将大量文件传递到该服务器而导致的拒绝服务攻击。指定的大小以 KB 为单位。默认值为 4096 KB (4 MB)。executionTimeout:指示在被 ASP.NET 自动关闭前,允许执行请求的最大秒数。在当文件超出指定的大小时,如果浏览器中会产生 DNS 错误或者出现服务不可得到的情况,也请修改以上的配置,把配置数加大。
另外,上载大文件时,还可能会收到以下错误信息:
<xmp> aspnet_wp.exe (PID: 1520) 被回收,因为内存消耗超过了 460 MB(可用 RAM 的百分之 60)。
</xmp>如果遇到此错误信息,请增加应用程序的 Web.config 文件的 <processmodel>元素中 memoryLimit 属性的值。例如:</processmodel>
<xmp><configuration><system.web><processmodel memorylimit="80"></processmodel></system.web></configuration></xmp>
分享到:
相关推荐
ASP.NET Web API File Upload and Multipart MIME
ASP.NET WebAPI 接口 实现单文件,多文件上传下载,图片缩略图访问实现接口,实用于APP,web系统应用,上传下载文件、图片访问分离处理。
Professional ASP.NET Web Services [Wrox 2001].pdf 我自己要学的资料。
最新的Pro ASP.NET Web API HTTP Web Services in ASP.NET; 英文高清pdf; 2013年新书,学习ASP.NET Web API 现阶段最权威的一本专业教材; 前置技能:C#(掌握) , MVC(掌握或了解) ,数据库(掌握),HTML(掌握)...
主要介绍了ASP.NET(C#) Web Api通过文件流下载文件的方法,提供源码下载,需要的朋友可以参考下。
ASP.NET 在WEBAPI中开发文件上传功能。以及MVC中如何调用
Asp.Net WebApi 上传文件方法: 实现功能: 1.原生js调用api上传 2.jq ajax调用api上传 上传文件
Author: Filip Wojcieszyn ISBN-10: 1430259809 Year: 2014 Pages: 408 Language: English ... Find out how you can build custom web services with ASP.NET Web API more efficiently than ever.
需求背景:以前在做文件上传下载,都是基于FrameWork项目或者Core Web项目实现的文件上传或下载,基于web的文件下载及权限比较好实现的。但是现在很多公司技术领导层,都在推行前后端分离理念,所以这一次我承担了...
《ASP.NET Web API设计》依托ASP.NET Web API阐述API设计与开发的通用技术,是一本全面介绍如何构建真实可演化API的实践指南。本书共分三部分。第一部分介绍Web/HTTP和API开发的基础知识,介绍ASP.NET Web API,为...
asp.net webapi2 的最新书籍,喜欢的同学可以拿去看看。
appdev ASP.NET web services 培训资料(pdf格式)
最新的Pro ASP.NET Web API HTTP Web Services in ASP.NET; 英文高清pdf; 2013年新书,学习ASP.NET Web API 现阶段最权威的一本专业教材; 前置技能:C#(掌握) , MVC(掌握或了解) ,数据库(掌握),HTML(掌握)...
WEBUPLOAD大文件传送C# asp.netWEBUPLOAD大文件传送C# asp.netWEBUPLOAD大文件传送C# asp.net
[上传下载]ASP.NET同时上传多个文件_aspxcnup.zip源码ASP.NET网站源码打包下载[上传下载]ASP.NET同时上传多个文件_aspxcnup.zip源码ASP.NET网站源码打包下载[上传下载]ASP.NET同时上传多个文件_aspxcnup.zip源码ASP...
在ASP,NET Web Services中如何来设定使用Session(HttpSessionState),以厦ASP.NET Web Services的客户端该如何才能让此Session正常运作采雏护状态
第1章 S101 一个简单的ASP.NET Web API应用 第2章 S201 通过路由实现请求地址与.aspx页面的映射 S202 基本路由注册 S203 在路由注册中指定约束 S204 针对现有物理文件的路由(关闭) S205 针对现有物理文件的...
主要为大家详细介绍了ASP.NET WebAPI连接数据库的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
基于jquery.form插件写的ASP.NET文件批量上传。
基于ASP.NET文件上传、下载的网络硬盘系统 源码