asp.net Web Services上傳和下載文件(完整代碼)
更新時(shí)間:2008年12月19日 12:40:45 作者:
隨著Internet技術(shù)的發(fā)展和跨平臺(tái)需求的日益增加,Web Services的應(yīng)用越來越廣,我們不但需要通過Web Services傳遞字符串信息,而且需要傳遞二進(jìn)制文件信息。
一旦我們創(chuàng)建了上面的asmx文件,進(jìn)行編譯后,我們就可以編寫客戶端的代碼來進(jìn)行調(diào)用這個(gè)Web Services了。
我們先“添加Web引用”,輸入:http://localhost/aspxWebCS/GetBinaryFile.asmx。下面,我們編寫顯示文件的中間文件:GetBinaryFileShow.aspx,這里,我們只需要在后代碼里編寫代碼即可,GetBinaryFileShow.aspx.cs文件內(nèi)容如下:
復(fù)制代碼 代碼如下:
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
{
///<summary>
///GetBinaryFileShow的摘要說明。
///</summary>
publicclassGetBinaryFileShow:System.Web.UI.Page
{
privatevoidPage_Load(objectsender,System.EventArgse)
{
//在此處放置用戶代碼以初始化頁面
///定義并初始化文件對(duì)象;
xml.sz.luohuedu.net.aspxWebCS.GetBinaryFile.ImagesoImage;
oImage=newxml.sz.luohuedu.net.aspxWebCS.GetBinaryFile.Images();
///得到二進(jìn)制文件字節(jié)數(shù)組;
byte[]image=oImage.GetImage("");
///轉(zhuǎn)換為支持存儲(chǔ)區(qū)為內(nèi)存的流
System.IO.MemoryStreammemStream=newSystem.IO.MemoryStream(image);
///定義并實(shí)例化Bitmap對(duì)象
Bitmapbm=newBitmap(memStream);
///根據(jù)不同的條件進(jìn)行輸出或者下載;
Response.Clear();
///如果請(qǐng)求字符串指定下載,就下載該文件;
///否則,就顯示在瀏覽器中。
if(Request.QueryString["Download"]=="1")
{
Response.Buffer=true;
Response.ContentType="application/octet-stream";
///這里下載輸出的文件名字ok.jpg為例子,你實(shí)際中可以根據(jù)情況動(dòng)態(tài)決定。
Response.AddHeader("Content-Disposition","attachment;filename=ok.jpg");
}
else
{
Response.ContentType=oImage.GetImageType();
Response.BinaryWrite(image);
Response.End();
}
}
#regionWebFormDesignergeneratedcode
overrideprotectedvoidOnInit(EventArgse)
{
//
//CODEGEN:該調(diào)用是ASP.NETWeb窗體設(shè)計(jì)器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
///<summary>
///設(shè)計(jì)器支持所需的方法-不要使用代碼編輯器修改
///此方法的內(nèi)容。
///</summary>
privatevoidInitializeComponent()
{
this.Load+=newSystem.EventHandler(this.Page_Load);
}
#endregion
}
}
最后,我們就編寫最終的瀏覽頁面:GetBinaryFile.aspx,這個(gè)文件很簡(jiǎn)單,只需要aspx文件即可,內(nèi)容如下:
復(fù)制代碼 代碼如下:
<%@Pagelanguage="c#"Codebehind="GetBinaryFile.aspx.cs"AutoEventWireup="false"Inherits="aspxWebCS.GetBinaryFile"%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.0Transitional//EN">
<HTML>
<HEAD>
<title>通過WebServices顯示和下載文件</title>
<metanamemetaname="GENERATOR"Content="MicrosoftVisualStudio7.0">
<metanamemetaname="CODE_LANGUAGE"Content="C#">
<metanamemetaname="vs_defaultClientScript"content="JavaScript">
<metanamemetaname="vs_targetSchema"content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<bodyMS_POSITIONINGbodyMS_POSITIONING="GridLayout">
<formidformid="GetBinaryFile"method="post"runat="server">
<FONTfaceFONTface="宋體">
<asp:HyperLinkidasp:HyperLinkid="HyperLink1"NavigateUrl="GetBinaryFileShow.aspx?Download=1"
runat="server">下載文件</asp:HyperLink>
<br/>
<!--下面是直接顯示文件-->
<asp:Imageidasp:Imageid="Image1"ImageUrl="GetBinaryFileShow.aspx"runat="server"></asp:Image>
</FONT>
</form>
</body>
</HTML>
二:通過Web Services上載文件
向服務(wù)器上載文件可能有許多種方法,在利用Web Services上載文件的方法中,下面的這個(gè)方法應(yīng)該是最簡(jiǎn)單的了。我們?nèi)韵笄懊娴睦幽菢樱紫冉pload.asmx文件,其Upload.asmx.cs內(nèi)容如下,里面已經(jīng)做了注釋:
復(fù)制代碼 代碼如下:
usingSystem;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Diagnostics;
usingSystem.Web;
usingSystem.Web.Services;
usingSystem.IO;
namespacexml.sz.luohuedu.net.aspxWebCS
{
///<summary>
///Upload的摘要說明。
///</summary>
[WebService(Namespace="http://xml.sz.luohuedu.net/",
Description="在WebServices里利用.NET框架進(jìn)上載文件。")]
publicclassUpload:System.Web.Services.WebService
{
publicUpload()
{
//CODEGEN:該調(diào)用是ASP.NETWeb服務(wù)設(shè)計(jì)器所必需的
InitializeComponent();
}
#regionComponentDesignergeneratedcode
//Web服務(wù)設(shè)計(jì)器所必需的
privateIContainercomponents=null;
///<summary>
///設(shè)計(jì)器支持所需的方法-不要使用代碼編輯器修改
///此方法的內(nèi)容。
///</summary>
privatevoidInitializeComponent()
{
}
///<summary>
///清理所有正在使用的資源。
///</summary>
protectedoverridevoidDispose(booldisposing)
{
if(disposing&&components!=null)
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
[WebMethod(Description="Web服務(wù)提供的方法,返回是否文件上載成功與否。")]
publicstringUploadFile(byte[]fs,stringFileName)
{
try
{
///定義并實(shí)例化一個(gè)內(nèi)存流,以存放提交上來的字節(jié)數(shù)組。
MemoryStreamm=newMemoryStream(fs);
///定義實(shí)際文件對(duì)象,保存上載的文件。
FileStreamf=newFileStream(Server.MapPath(".")+"\\"
+FileName,FileMode.Create);
///把內(nèi)內(nèi)存里的數(shù)據(jù)寫入物理文件
m.WriteTo(f);
m.Close();
f.Close();
f=null;
m=null;
return"文件已經(jīng)上傳成功。";
}
catch(Exceptionex)
{
returnex.Message;
}
}
}
}
要上載文件,必須提供一個(gè)表單,來供用戶進(jìn)行文件的選擇,下面我們就建立這樣一個(gè)頁面Upload.aspx,用來提供文件上載:
復(fù)制代碼 代碼如下:
<%@Pagelanguage="c#" Codebehind="Upload.aspx.cs" AutoEventWireup="false" Inherits="aspxWebCS.Upload"%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.0Transitional//EN">
<HTML>
<HEAD>
<title>通過WebServices上載文件</title>
<metanamemetaname="GENERATOR"content="MicrosoftVisualStudio.NET7.0">
<metanamemetaname="CODE_LANGUAGE"content="VisualBasic7.0">
<metanamemetaname="vs_defaultClientScript"content="JavaScript">
<metanamemetaname="vs_targetSchema"content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<bodyMS_POSITIONINGbodyMS_POSITIONING="GridLayout">
<formidformid="Form1"method="post"runat="server"enctype="multipart/form-data">
<INPUTidINPUTid="MyFile"type="file"runat="server">
<br>
<br>
<asp:Buttonidasp:Buttonid="Button1"runat="server"Text="上載文件"></asp:Button>
</form>
</body>
</HTML>
我們要進(jìn)行處理的是在后代碼里面,下面詳細(xì)的介紹,Upload.aspx.cs:.
復(fù)制代碼 代碼如下:
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
{
///<summary>
///Upload的摘要說明。
///利用該方法通過WebServices上載文件
///</summary>
publicclassUpload:System.Web.UI.Page
{
protectedSystem.Web.UI.HtmlControls.HtmlInputFileMyFile;
protectedSystem.Web.UI.WebControls.ButtonButton1;
privatevoidPage_Load(objectsender,System.EventArgse)
{
//在此處放置用戶代碼以初始化頁面
}
#regionWebFormDesignergeneratedcode
overrideprotectedvoidOnInit(EventArgse)
{
//
//CODEGEN:該調(diào)用是ASP.NETWeb窗體設(shè)計(jì)器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
///<summary>
///設(shè)計(jì)器支持所需的方法-不要使用代碼編輯器修改
///此方法的內(nèi)容。
///</summary>
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("請(qǐng)選擇文件。");
Response.End();
}
stringFilePath=oFiles[0].FileName;
if(FilePath==""||FilePath==null)
{
Response.Write("請(qǐng)選擇一個(gè)文件。");
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);
///調(diào)用WebServices的UploadFile方法進(jìn)行上載文件。
Response.Write(o.UploadFile(b,FileName));
fs.Close();
}
catch(Exceptionex)
{
Response.Write(ex.Message);
}
}
else
{
Response.Write("請(qǐng)選擇文件");
}
}
}
}
最后,需要注意的是:在保存文件時(shí),您應(yīng)該確保指定文件的完整路徑(例如,"C:\MyFiles\Picture.jpg"),并確保為 ASP.NET 使用的帳戶提供要存儲(chǔ)文件的目錄的寫權(quán)限。上載大文件時(shí),可使用 元素的 maxRequestLength 屬性來增加文件大小的最大允許值,例如:
復(fù)制代碼 代碼如下:
<configuration>
<system.web>
<httpRuntime maxRequestLength="1048576" executionTimeout="3600" />
</system.web>
</configuration>
其中:maxRequestLength:指示 ASP.NET 支持的HTTP方式上載的最大字節(jié)數(shù)。該限制可用于防止因用戶將大量文件傳遞到該服務(wù)器而導(dǎo)致的拒絕服務(wù)攻擊。指定的大小以 KB 為單位。默認(rèn)值為 4096 KB (4 MB)。executionTimeout:指示在被 ASP.NET 自動(dòng)關(guān)閉前,允許執(zhí)行請(qǐng)求的最大秒數(shù)。在當(dāng)文件超出指定的大小時(shí),如果瀏覽器中會(huì)產(chǎn)生 DNS 錯(cuò)誤或者出現(xiàn)服務(wù)不可得到的情況,也請(qǐng)修改以上的配置,把配置數(shù)加大。
另外,上載大文件時(shí),還可能會(huì)收到以下錯(cuò)誤信息:
aspnet_wp.exe (PID: 1520) 被回收,因?yàn)閮?nèi)存消耗超過了 460 MB(可用 RAM 的百分之 60)。
如果遇到此錯(cuò)誤信息,請(qǐng)?jiān)黾討?yīng)用程序的 Web.config 文件的 元素中 memoryLimit 屬性的值。例如:
復(fù)制代碼 代碼如下:
<configuration>
<system.web>
<processModel memoryLimit="80"/>
</system.web>
</configuration>
我在自己的機(jī)器上測(cè)試,可以上傳50M以上的文件。以上代碼在Windows XP + .NET 1.0 + VS.NET2002下測(cè)試通過。
您可能感興趣的文章:
- ASP.NET Core文件上傳與下載實(shí)例(多種上傳方式)
- 擁有網(wǎng)頁版小U盤 ASP.NET實(shí)現(xiàn)文件上傳與下載功能
- asp.net+jquery.form實(shí)現(xiàn)圖片異步上傳的方法(附j(luò)query.form.js下載)
- Asp.net實(shí)現(xiàn)MVC處理文件的上傳下載功能實(shí)例教程
- asp.net 多文件上傳,兼容IE6/7/8,提供完整代碼下載
- asp.net 上傳或下載當(dāng)文件名包含有特殊字符"#"的處理
- asp.net 上傳下載輸出二進(jìn)制流實(shí)現(xiàn)代碼
- ASP.NET中文件上傳下載方法集合
- ASP.NET實(shí)現(xiàn)文件上傳功能
- ASP.NET Core實(shí)現(xiàn)文件上傳和下載
相關(guān)文章
ADO.Net對(duì)oracle數(shù)據(jù)庫操作的實(shí)例代碼
ADO.Net對(duì)oracle數(shù)據(jù)庫操作的實(shí)例代碼,需要的朋友可以參考一下2013-06-06關(guān)于VS2012自帶的 性能分析 工具使用實(shí)例(圖文介紹)
本篇文章小編為大家介紹,關(guān)于VS2012自帶的 性能分析 工具使用實(shí)例(圖文介紹),需要的朋友參考下2013-04-04asp.net LC.exe已退出代碼為 -1的原因分析及解決方法
錯(cuò)誤“LC.exe”已退出,代碼為 -1。是VS2005,并且在項(xiàng)目中引用了第三方組件。2013-06-06建立自定義的數(shù)據(jù)驅(qū)動(dòng)的本地化資源provider
本文探討了自定義的本地化資源提供者.如果想用一個(gè)可替代系統(tǒng)的資源處理方案,例如把所有的資源放入數(shù)據(jù)庫中,而不是放在分散的資源文件里,你可以自定義一個(gè)resource provider.2010-06-06.NET 中英文混合驗(yàn)證碼實(shí)現(xiàn)代碼
.NET 中英文混合驗(yàn)證碼實(shí)現(xiàn)代碼2009-11-11ASP.NET 2.0 程序安全的基礎(chǔ)知識(shí)
成員關(guān)系的概念在人類社會(huì)中是一個(gè)層次比較低的概念,源于希望屬于某個(gè)群組的意識(shí)。同樣,在ASP.NET 2.0程序開始開發(fā)涉及到成員關(guān)系的應(yīng)用程序時(shí),必須首先理解身份、驗(yàn)證和授權(quán)這幾個(gè)關(guān)鍵的概念。2010-04-04ASP.NET oledb連接Access數(shù)據(jù)庫的方法
這篇文章主要介紹了ASP.NET oledb連接Access數(shù)據(jù)庫的方法,需要的朋友可以參考下2015-01-01