欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

asp.net Web Services上傳和下載文件(完整代碼)

 更新時間:2008年12月19日 12:40:45   作者:  
隨著Internet技術(shù)的發(fā)展和跨平臺需求的日益增加,Web Services的應(yīng)用越來越廣,我們不但需要通過Web Services傳遞字符串信息,而且需要傳遞二進制文件信息。

一旦我們創(chuàng)建了上面的asmx文件,進行編譯后,我們就可以編寫客戶端的代碼來進行調(diào)用這個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)
{
//在此處放置用戶代碼以初始化頁面
///定義并初始化文件對象;
xml.sz.luohuedu.net.aspxWebCS.GetBinaryFile.ImagesoImage;
oImage=newxml.sz.luohuedu.net.aspxWebCS.GetBinaryFile.Images();
///得到二進制文件字節(jié)數(shù)組;
byte[]image=oImage.GetImage("");
///轉(zhuǎn)換為支持存儲區(qū)為內(nèi)存的流
System.IO.MemoryStreammemStream=newSystem.IO.MemoryStream(image);
///定義并實例化Bitmap對象
Bitmapbm=newBitmap(memStream);
///根據(jù)不同的條件進行輸出或者下載;
Response.Clear();
///如果請求字符串指定下載,就下載該文件;
///否則,就顯示在瀏覽器中。
if(Request.QueryString["Download"]=="1")
{
Response.Buffer=true;
Response.ContentType="application/octet-stream";
///這里下載輸出的文件名字ok.jpg為例子,你實際中可以根據(jù)情況動態(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è)計器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

///<summary>
///設(shè)計器支持所需的方法-不要使用代碼編輯器修改
///此方法的內(nèi)容。
///</summary>
privatevoidInitializeComponent()
{
this.Load+=newSystem.EventHandler(this.Page_Load);
}
#endregion
}
}

最后,我們就編寫最終的瀏覽頁面:GetBinaryFile.aspx,這個文件很簡單,只需要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上載文件的方法中,下面的這個方法應(yīng)該是最簡單的了。我們?nèi)韵笄懊娴睦幽菢?,首先建立Upload.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框架進上載文件。")]
publicclassUpload:System.Web.Services.WebService
{
publicUpload()
{
//CODEGEN:該調(diào)用是ASP.NETWeb服務(wù)設(shè)計器所必需的
InitializeComponent();
}
#regionComponentDesignergeneratedcode
//Web服務(wù)設(shè)計器所必需的
privateIContainercomponents=null;
///<summary>
///設(shè)計器支持所需的方法-不要使用代碼編輯器修改
///此方法的內(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
{
///定義并實例化一個內(nèi)存流,以存放提交上來的字節(jié)數(shù)組。
MemoryStreamm=newMemoryStream(fs);
///定義實際文件對象,保存上載的文件。
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;
}
}
}
}

要上載文件,必須提供一個表單,來供用戶進行文件的選擇,下面我們就建立這樣一個頁面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>

我們要進行處理的是在后代碼里面,下面詳細的介紹,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è)計器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

///<summary>
///設(shè)計器支持所需的方法-不要使用代碼編輯器修改
///此方法的內(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("請選擇文件。");
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);
///調(diào)用WebServices的UploadFile方法進行上載文件。
Response.Write(o.UploadFile(b,FileName));
fs.Close();
}
catch(Exceptionex)
{
Response.Write(ex.Message);
}
}
else
{
Response.Write("請選擇文件");
}
}
}
}

最后,需要注意的是:在保存文件時,您應(yīng)該確保指定文件的完整路徑(例如,"C:\MyFiles\Picture.jpg"),并確保為 ASP.NET 使用的帳戶提供要存儲文件的目錄的寫權(quán)限。上載大文件時,可使用 元素的 maxRequestLength 屬性來增加文件大小的最大允許值,例如:
復(fù)制代碼 代碼如下:

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

其中:maxRequestLength:指示 ASP.NET 支持的HTTP方式上載的最大字節(jié)數(shù)。該限制可用于防止因用戶將大量文件傳遞到該服務(wù)器而導(dǎo)致的拒絕服務(wù)攻擊。指定的大小以 KB 為單位。默認值為 4096 KB (4 MB)。executionTimeout:指示在被 ASP.NET 自動關(guān)閉前,允許執(zhí)行請求的最大秒數(shù)。在當(dāng)文件超出指定的大小時,如果瀏覽器中會產(chǎn)生 DNS 錯誤或者出現(xiàn)服務(wù)不可得到的情況,也請修改以上的配置,把配置數(shù)加大。
另外,上載大文件時,還可能會收到以下錯誤信息:
aspnet_wp.exe (PID: 1520) 被回收,因為內(nèi)存消耗超過了 460 MB(可用 RAM 的百分之 60)。
如果遇到此錯誤信息,請增加應(yīng)用程序的 Web.config 文件的 元素中 memoryLimit 屬性的值。例如:
復(fù)制代碼 代碼如下:

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

我在自己的機器上測試,可以上傳50M以上的文件。以上代碼在Windows XP + .NET 1.0 + VS.NET2002下測試通過。

相關(guān)文章

最新評論