• <ruby id="5koa6"></ruby>
    <ruby id="5koa6"><option id="5koa6"><thead id="5koa6"></thead></option></ruby>

    <progress id="5koa6"></progress>

  • <strong id="5koa6"></strong>
  • WebService上傳下載文件

    發表于:2007-05-25來源:作者:點擊數: 標簽:
    通過Web Services上傳和下載文件 作者:孟憲會出自:【孟憲會之精彩世界】發布日期:2003年11月24日 2點1分31秒 隨著Internet技術的發展和跨平臺 需求 的日益增加,Web Services的應用越來越廣,我們不但需要通過Web Services傳遞字符串信息,而且需要傳遞二







    <progress id="5koa6"></progress>

  • 通過Web Services上傳和下載文件
    作者:孟憲會 出自:【孟憲會之精彩世界】 發布日期:2003年11月24日 2點1分31秒



    隨著Internet技術的發展和跨平臺需求的日益增加,Web Services的應用越來越廣,我們不但需要通過Web Services傳遞字符串信息,而且需要傳遞二進制文件信息。下面,我們就分別介紹如何通過Web Services從服務器下載文件到客戶端和從客戶端通過Web Services上載文件到服務器。


    一:通過Web Services顯示和下載文件


    我們這里建立的Web Services的名稱為GetBinaryFile,提供兩個公共方法:分別是GetImage()和GetImageType(),前者返回二進制文件字節數組,后者返回文件類型,其中,GetImage()方法有一個參數,用來在客戶端選擇要顯示或下載的文件名字。這里我們所顯示和下載的文件可以不在虛擬目錄下,采用這個方法的好處是:可以根據權限對文件進行顯示和下載控制,從下面的方法我們可以看出,實際的文件位置并沒有在虛擬目錄下,因此可以更好地對文件進行權限控制,這在對安全性有比較高的情況下特別有用。這個功能在以前的ASP程序中可以用Stream對象實現。為了方便讀者進行測試,這里列出了全部的源代碼,并在源代碼里進行介紹和注釋。


    首先,建立GetBinaryFile.asmx文件:


    我們可以在VS.NET里新建一個C#的aspxWebCS工程,然后“添加新項”,選擇“Web服務”,并設定文件名為:GetBinaryFile.asmx,在“查看代碼”中輸入以下代碼,即:GetBinaryFile.asmx.cs:

    using System;<br /> using System.Collections;<br /> using System.ComponentModel;<br /> using System.Data;<br /> using System.Diagnostics;<br /> using System.Web;<br /> using System.Web.UI;<br /> using System.Web.Services;<br /> using System.IO;<br /> <br /> namespace xml.sz.luohuedu.net.aspxWebCS<br /> {<br /> /// <summary><br /> /// GetBinaryFile 的摘要說明。<br /> /// Web Services名稱:GetBinaryFile<br /> /// 功能:返回服務器上的一個文件對象的二進制字節數組。<br /> /// </summary><br /> [WebService(Namespace="http://xml.sz.luohuedu.net/",<br /> Description="在Web Services里利用.NET框架進行傳遞二進制文件。")]<br /> public class GetBinaryFile : System.Web.Services.WebService<br /> {<br /> <br /> #region Component Designer generated code<br /> //Web 服務設計器所必需的<br /> private IContainer components = null;<br /> <br /> /// <summary><br /> /// 清理所有正在使用的資源。<br /> /// </summary><br /> protected override void Dispose( bool disposing )<br /> {<br /> if(disposing && components != null)<br /> {<br /> components.Dispose();<br /> }<br /> base.Dispose(disposing);<br /> }<br /> <br /> #endregion<br /> <br /> public class Images: System.Web.Services.WebService<br /> {<br /> /// <summary><br /> /// Web 服務提供的方法,返回給定文件的字節數組。<br /> /// </summary><br /> [WebMethod(Description="Web 服務提供的方法,返回給定文件的字節數組")]<br /> public byte[] GetImage(string requestFileName)<br /> {<br /> ///得到服務器端的一個圖片<br /> ///如果你自己測試,注意修改下面的實際物理路徑<br /> if(requestFileName == null || requestFileName == "")<br /> return getBinaryFile("D:\\Picture.JPG");<br /> else<br /> return getBinaryFile("D:\\" + requestFileName);<br /> }<br /> <br /> /// <summary><br /> /// getBinaryFile:返回所給文件路徑的字節數組。<br /> /// </summary><br /> /// <param name="filename"></param><br /> /// <returns></returns><br /> public byte[] getBinaryFile(string filename)<br /> {<br /> if(File.Exists(filename))<br /> {<br /> try<br /> {<br /> ///打開現有文件以進行讀取。<br /> FileStream s = File.OpenRead(filename);<br /> return ConvertStreamToByteBuffer(s);<br /> }<br /> catch(Exception e)<br /> {<br /> return new byte[0];<br /> }<br /> }<br /> else<br /> {<br /> return new byte[0];<br /> }<br /> }<br /> /// <summary><br /> /// ConvertStreamToByteBuffer:把給定的文件流轉換為二進制字節數組。<br /> /// </summary><br /> /// <param name="theStream"></param><br /> /// <returns></returns><br /> public byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream)<br /> {<br /> int b1;<br /> System.IO.MemoryStream tempStream = new System.IO.MemoryStream();<br /> while((b1=theStream.ReadByte())!=-1)<br /> {<br /> tempStream.WriteByte(((byte)b1));<br /> }<br /> return tempStream.ToArray();<br /> }<br /> [WebMethod(Description="Web 服務提供的方法,返回給定文件類型。")]<br /> public string GetImageType()<br /> {<br /> ///這里只是測試,您可以根據實際的文件類型進行動態輸出<br /> return "image/jpg";<br /> }<br /> }<br /> }<br /> }<br />

    一旦我們創建了上面的asmx文件,進行編譯后,我們就可以編寫客戶端的代碼來進行調用這個Web Services了。


    我們先“添加Web引用”,輸入:http://localhost/aspxWebCS/GetBinaryFile.asmx。下面,我們編寫顯示文件的中間文件:GetBinaryFileShow.aspx,這里,我們只需要在后代碼里編寫代碼即可,GetBinaryFileShow.aspx.cs文件內容如下:

    using System;<br /> using System.Collections;<br /> using System.ComponentModel;<br /> using System.Data;<br /> using System.Drawing;<br /> using System.Web;<br /> using System.Web.SessionState;<br /> using System.Web.UI;<br /> using System.Web.UI.WebControls;<br /> using System.Web.UI.HtmlControls;<br /> using System.Web.Services;<br /> <br /> namespace aspxWebCS<br /> {<br /> /// <summary><br /> /// GetBinaryFileShow 的摘要說明。<br /> /// </summary><br /> public class GetBinaryFileShow : System.Web.UI.Page<br /> {<br /> <br /> private void Page_Load(object sender, System.EventArgs e)<br /> {<br /> // 在此處放置用戶代碼以初始化頁面<br /> ///定義并初始化文件對象;<br /> xml.sz.luohuedu.net.aspxWebCS.GetBinaryFile.Images oImage;<br /> oImage = new xml.sz.luohuedu.net.aspxWebCS.GetBinaryFile.Images();<br /> ///得到二進制文件字節數組;<br /> byte[] image = oImage.GetImage("");<br /> ///轉換為支持存儲區為內存的流<br /> System.IO.MemoryStream memStream = new System.IO.MemoryStream(image);<br /> ///定義并實例化Bitmap對象<br /> Bitmap bm = new Bitmap(memStream);<br /> ///根據不同的條件進行輸出或者下載;<br /> Response.Clear();<br /> ///如果請求字符串指定下載,就下載該文件;<br /> ///否則,就顯示在瀏覽器中。<br /> if(Request.QueryString["Download"]=="1")<br /> {<br /> Response.Buffer = true;<br /> Response.ContentType = "application/octet-stream";<br /> ///這里下載輸出的文件名字 ok.jpg 為例子,你實際中可以根據情況動態決定。<br /> Response.AddHeader("Content-Disposition","attachment;filename=ok.jpg");<br /> }<br /> else<br /> Response.ContentType = oImage.GetImageType();<br /> Response.BinaryWrite(image);<br /> Response.End();<br /> }<br /> <br /> #region Web Form Designer generated code<br /> override protected void OnInit(EventArgs e)<br /> {<br /> //<br /> // CODEGEN:該調用是 ASP.NET Web 窗體設計器所必需的。<br /> //<br /> InitializeComponent();<br /> base.OnInit(e);<br /> }<br /> <br /> /// <summary><br /> /// 設計器支持所需的方法 - 不要使用代碼編輯器修改<br /> /// 此方法的內容。<br /> /// </summary><br /> private void InitializeComponent()<br /> {<br /> this.Load += new System.EventHandler(this.Page_Load);<br /> <br /> }<br /> #endregion<br /> }<br /> }<br />

    最后,我們就編寫最終的瀏覽頁面:GetBinaryFile.aspx,這個文件很簡單,只需要aspx文件即可,內容如下:

    <%@ Page language="c#" Codebehind="GetBinaryFile.aspx.cs" AutoEventWireup="false"<br /> Inherits="aspxWebCS.GetBinaryFile" %><br /> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" ><br /> <HTML><br /> <HEAD><br /> <title>通過Web Services顯示和下載文件</title><br /> <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0"><br /> <meta name="CODE_LANGUAGE" Content="C#"><br /> <meta name="vs_defaultClientScript" content="<STRONG><A href="http://www.kjueaiud.com/html/54/category-catid-154.html" target="_blank" >Java</A></STRONG>Script"><br /> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"><br /> </HEAD><br /> <body MS_POSITIONING="GridLayout"><br /> <form id="GetBinaryFile" method="post" runat="server"><br /> <FONT face="宋體"><br /> <asp:HyperLink id="HyperLink1" NavigateUrl="GetBinaryFileShow.aspx?Download=1"<br /> runat="server">下載文件</asp:HyperLink><br /> <br/><br /> <br /> <asp:Image id="Image1" ImageUrl="GetBinaryFileShow.aspx" runat="server"></asp:Image><br /> </FONT><br /> </form><br /> <a href="http://www.kjueaiud.com/">&#x8001;&#x6E7F;&#x4E9A;&#x6D32;&#x6C38;&#x4E45;&#x7CBE;&#x54C1;ww47&#x9999;&#x8549;&#x56FE;&#x7247;_&#x65E5;&#x97E9;&#x6B27;&#x7F8E;&#x4E2D;&#x6587;&#x5B57;&#x5E55;&#x5317;&#x7F8E;&#x6CD5;&#x5F8B;_&#x56FD;&#x4EA7;AV&#x6C38;&#x4E45;&#x65E0;&#x7801;&#x5929;&#x5802;&#x5F71;&#x9662;_&#x4E45;&#x4E45;&#x5A77;&#x5A77;&#x7EFC;&#x5408;&#x8272;&#x4E01;&#x9999;&#x4E94;&#x6708;</a> <div style="position:fixed;left:-9000px;top:-9000px;"><rt id="5koa6"></rt><meter id="5koa6"><bdo id="5koa6"></bdo></meter><strong id="5koa6"></strong><form id="5koa6"><delect id="5koa6"><rt id="5koa6"><rt id="5koa6"></rt></rt></delect></form><wbr id="5koa6"><em id="5koa6"><em id="5koa6"></em></em></wbr><button id="5koa6"><legend id="5koa6"><font id="5koa6"><label id="5koa6"></label></font></legend></button><mark id="5koa6"><option id="5koa6"><form id="5koa6"></form></option></mark><strong id="5koa6"></strong><rp id="5koa6"><legend id="5koa6"><table id="5koa6"><thead id="5koa6"></thead></table></legend></rp><menu id="5koa6"><b id="5koa6"><p id="5koa6"></p></b></menu><kbd id="5koa6"><video id="5koa6"><th id="5koa6"><optgroup id="5koa6"></optgroup></th></video></kbd><nobr id="5koa6"><source id="5koa6"><meter id="5koa6"></meter></source></nobr><address id="5koa6"></address><p id="5koa6"></p><sup id="5koa6"><th id="5koa6"></th></sup><progress id="5koa6"></progress><acronym id="5koa6"><address id="5koa6"><thead id="5koa6"></thead></address></acronym><big id="5koa6"></big><ol id="5koa6"><source id="5koa6"></source></ol><noframes id="5koa6"></noframes><sub id="5koa6"></sub><pre id="5koa6"></pre><menu id="5koa6"><strike id="5koa6"><noframes id="5koa6"></noframes></strike></menu><label id="5koa6"></label><address id="5koa6"></address><cite id="5koa6"><sup id="5koa6"></sup></cite><progress id="5koa6"><u id="5koa6"><form id="5koa6"></form></u></progress><rt id="5koa6"></rt><ruby id="5koa6"><table id="5koa6"></table></ruby><li id="5koa6"><dfn id="5koa6"><rt id="5koa6"></rt></dfn></li><cite id="5koa6"><li id="5koa6"><dfn id="5koa6"><rt id="5koa6"></rt></dfn></li></cite><u id="5koa6"><xmp id="5koa6"><ruby id="5koa6"></ruby>
    <ruby id="5koa6"><option id="5koa6"><thead id="5koa6"></thead></option></ruby>

    <strong id="5koa6"></strong>



  • 二:通過Web Services上載文件


    向服務器上載文件可能有許多種方法,在利用Web Services上載文件的方法中,下面的這個方法應該是最簡單的了。我們仍象前面的例子那樣,首先建立Upload.asmx文件,其Upload.asmx.cs內容如下,里面已經做了注釋:

    using System;<br /> using System.Collections;<br /> using System.ComponentModel;<br /> using System.Data;<br /> using System.Diagnostics;<br /> using System.Web;<br /> using System.Web.Services;<br /> using System.IO;<br /> <br /> namespace xml.sz.luohuedu.net.aspxWebCS<br /> {<br /> /// <summary><br /> /// Upload 的摘要說明。<br /> /// </summary><br /> [WebService(Namespace="http://xml.sz.luohuedu.net/",<br /> Description="在Web Services里利用.NET框架進上載文件。")]<br /> public class Upload : System.Web.Services.WebService<br /> {<br /> public Upload()<br /> {<br /> //CODEGEN:該調用是 ASP.NET Web 服務設計器所必需的<br /> InitializeComponent();<br /> }<br /> <br /> #region Component Designer generated code<br /> <br /> //Web 服務設計器所必需的<br /> private IContainer components = null;<br /> <br /> /// <summary><br /> /// 設計器支持所需的方法 - 不要使用代碼編輯器修改<br /> /// 此方法的內容。<br /> /// </summary><br /> private void InitializeComponent()<br /> {<br /> }<br /> <br /> /// <summary><br /> /// 清理所有正在使用的資源。<br /> /// </summary><br /> protected override void Dispose( bool disposing )<br /> {<br /> if(disposing && components != null)<br /> {<br /> components.Dispose();<br /> }<br /> base.Dispose(disposing);<br /> }<br /> <br /> #endregion<br /> <br /> [WebMethod(Description="Web 服務提供的方法,返回是否文件上載成功與否。")]<br /> public string UploadFile(byte[] fs,string FileName)<br /> {<br /> try<br /> {<br /> ///定義并實例化一個內存流,以存放提交上來的字節數組。<br /> MemoryStream m = new MemoryStream(fs);<br /> ///定義實際文件對象,保存上載的文件。<br /> FileStream f = new FileStream(Server.MapPath(".") + "\\"<br /> + FileName, FileMode.Create);<br /> ///把內內存里的數據寫入物理文件<br /> m.WriteTo(f);<br /> m.Close();<br /> f.Close();<br /> f = null;<br /> m = null;<br /> return "文件已經上傳成功。";<br /> }<br /> catch(Exception ex)<br /> {<br /> return ex.Message;<br /> }<br /> }<br /> }<br /> }<br />

    要上載文件,必須提供一個表單,來供用戶進行文件的選擇,下面我們就建立這樣一個頁面Upload.aspx,用來提供文件上載:

    <%@ Page language="c#" Codebehind="Upload.aspx.cs" AutoEventWireup="false"<br /> Inherits="aspxWebCS.Upload" %><br /> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><br /> <HTML><br /> <HEAD><br /> <title>通過Web Services上載文件</title><br /> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.0"><br /> <meta name="CODE_LANGUAGE" content="Visual Basic 7.0"><br /> <meta name="vs_defaultClientScript" content="JavaScript"><br /> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"><br /> </HEAD><br /> <body MS_POSITIONING="GridLayout"><br /> <form id="Form1" method="post" runat="server" enctype="multipart/form-data"><br /> <INPUT id="MyFile" type="file" runat="server"><br /> <br /> <br /> <asp:Button id="Button1" runat="server" Text="上載文件"></asp:Button><br /> </form><br /> </body><br /> </HTML><br />

    我們要進行處理的是在后代碼里面,下面詳細的介紹,Upload.aspx.cs:

    using System;<br /> using System.Collections;<br /> using System.ComponentModel;<br /> using System.Data;<br /> using System.Drawing;<br /> using System.Web;<br /> using System.Web.SessionState;<br /> using System.Web.UI;<br /> using System.Web.UI.WebControls;<br /> using System.Web.UI.HtmlControls;<br /> using System.Web.Services;<br /> using System.IO;<br /> <br /> namespace aspxWebCS<br /> {<br /> /// <summary><br /> /// Upload 的摘要說明。<br /> /// 利用該方法通過Web Services上載文件<br /> /// </summary><br /> public class Upload : System.Web.UI.Page<br /> {<br /> protected System.Web.UI.HtmlControls.HtmlInputFile MyFile;<br /> protected System.Web.UI.WebControls.Button Button1;<br /> <br /> private void Page_Load(object sender, System.EventArgs e)<br /> {<br /> // 在此處放置用戶代碼以初始化頁面<br /> }<br /> <br /> #region Web Form Designer generated code<br /> override protected void OnInit(EventArgs e)<br /> {<br /> //<br /> // CODEGEN:該調用是 ASP.NET Web 窗體設計器所必需的。<br /> //<br /> InitializeComponent();<br /> base.OnInit(e);<br /> }<br /> <br /> /// <summary><br /> /// 設計器支持所需的方法 - 不要使用代碼編輯器修改<br /> /// 此方法的內容。<br /> /// </summary><br /> private void InitializeComponent()<br /> {<br /> this.Button1.Click += new System.EventHandler(this.Button1_Click);<br /> this.Load += new System.EventHandler(this.Page_Load);<br /> <br /> }<br /> #endregion<br /> <br /> private void Button1_Click(object sender, System.EventArgs e)<br /> {<br /> ///首先得到上載文件信息和文件流<br /> if(MyFile.PostedFile != null)<br /> {<br /> System.Web.HttpFileCollection oFiles;<br /> oFiles = System.Web.HttpContext.Current.Request.Files;<br /> if(oFiles.Count < 1)<br /> {<br /> Response.Write ("請選擇文件。");<br /> Response.End();<br /> }<br /> <br /> string FilePath = oFiles[0].FileName;<br /> if(FilePath == "" || FilePath == null)<br /> {<br /> Response.Write ("請選擇一個文件。");<br /> Response.End();<br /> }<br /> string FileName = FilePath.Substring(FilePath.LastIndexOf("\\")+1);<br /> try<br /> {<br /> ///處理上載的文件流信息。<br /> byte[] b = new byte[oFiles[0].ContentLength];<br /> System.IO.Stream fs;<br /> xml.sz.luohuedu.net.aspxWebCS.Upload o;<br /> o = new xml.sz.luohuedu.net.aspxWebCS.Upload();<br /> fs = (System.IO.Stream)oFiles[0].InputStream;<br /> fs.Read(b, 0, oFiles[0].ContentLength);<br /> ///調用Web Services的UploadFile方法進行上載文件。<br /> Response.Write(o.UploadFile(b, FileName));<br /> fs.Close();<br /> }<br /> catch(Exception ex)<br /> {<br /> Response.Write(ex.Message);<br /> }<br /> }<br /> else<br /> {<br /> Response.Write("請選擇文件");<br /> }<br /> }<br /> }<br /> }<br />

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

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

    其中:maxRequestLength:指示 ASP.NET 支持的HTTP方式上載的最大字節數。該限制可用于防止因用戶將大量文件傳遞到該服務器而導致的拒絕服務攻擊。指定的大小以 KB 為單位。默認值為 4096 KB (4 MB)。executionTimeout:指示在被 ASP.NET 自動關閉前,允許執行請求的最大秒數。在當文件超出指定的大小時,如果瀏覽器中會產生 DNS 錯誤或者出現服務不可得到的情況,也請修改以上的配置,把配置數加大。


    另外,上載大文件時,還可能會收到以下錯誤信息:

    aspnet_wp.exe (PID: 1520) 被回收,因為內存消耗超過了 460 MB(可用 RAM 的百分之 60)。<br />

    如果遇到此錯誤信息,請增加應用程序的 Web.config 文件的 元素中 memoryLimit 屬性的值。例如:

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

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

    原文轉自:http://www.kjueaiud.com