轉 2003年的 asp.net webservices 上傳下載文件

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

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

首先,建立GetBinaryFile.asmx文件:

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

  1. using System;
  2.     using System.Collections;
  3.     using System.ComponentModel;
  4.     using System.Data;
  5.     using System.Diagnostics;
  6.     using System.Web;
  7.     using System.Web.UI;
  8.     using System.Web.Services;
  9.     using System.IO;
  10.     namespace xml.sz.luohuedu.net.aspxWebCS
  11.     {
  12.         /// <summary>
  13.         /// GetBinaryFile 的摘要說明。
  14.         /// Web Services名稱:GetBinaryFile
  15.         /// 功能:返回服務器上的一個文件對象的二進制字節數組。
  16.         /// </summary>
  17.     [WebService(Namespace="http://xml.sz.luohuedu.net/",
  18.         Description="在Web Services裏利用.NET框架進行傳遞二進制文件。")]
  19.         public class GetBinaryFile : System.Web.Services.WebService
  20.         {
  21.             #region Component Designer generated code
  22.             //Web 服務設計器所必需的
  23.             private IContainer components = null;
  24.             /// <summary>
  25.             /// 清理所有正在使用的資源。
  26.             /// </summary>
  27.             protected override void Dispose( bool disposing )
  28.             {
  29.                 if(disposing && components != null)
  30.                 {
  31.                     components.Dispose();
  32.                 }
  33.                 base.Dispose(disposing);
  34.             }
  35.             #endregion
  36.        public class Images: System.Web.Services.WebService
  37.       {
  38.        /// <summary>
  39.        /// Web 服務提供的方法,返回給定文件的字節數組。
  40.        /// </summary>
  41.        [WebMethod(Description="Web 服務提供的方法,返回給定文件的字節數組")]
  42.        public byte[] GetImage(string requestFileName)
  43.        {
  44.         ///得到服務器端的一個圖片
  45.         ///如果你自己測試,注意修改下面的實際物理路徑
  46.         if(requestFileName == null || requestFileName == "")
  47.          return getBinaryFile("D://Picture.JPG");
  48.         else
  49.          return getBinaryFile("D://" + requestFileName);
  50.        }
  51.        /// <summary>
  52.        /// getBinaryFile:返回所給文件路徑的字節數組。
  53.        /// </summary>
  54.        /// <param name="filename"></param>
  55.        /// <returns></returns>
  56.        public byte[] getBinaryFile(string filename)
  57.        {
  58.         if(File.Exists(filename))
  59.         {
  60.          try
  61.          {
  62.           ///打開現有文件以進行讀取。
  63.           FileStream s = File.OpenRead(filename);
  64.           return ConvertStreamToByteBuffer(s);
  65.          }
  66.          catch(Exception e)
  67.          {
  68.           return new byte[0];
  69.          }
  70.         }
  71.         else
  72.         {
  73.          return new byte[0];
  74.         }
  75.        }
  76.      /// <summary>
  77.      /// ConvertStreamToByteBuffer:把給定的文件流轉換爲二進制字節數組。
  78.      /// </summary>
  79.      /// <param name="theStream"></param>
  80.      /// <returns></returns>
  81.        public byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream)
  82.        {
  83.         int b1;
  84.         System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
  85.         while((b1=theStream.ReadByte())!=-1)
  86.         {
  87.          tempStream.WriteByte(((byte)b1));
  88.         }
  89.         return tempStream.ToArray();
  90.        }
  91.         [WebMethod(Description="Web 服務提供的方法,返回給定文件類型。")]
  92.         public string GetImageType()
  93.         {
  94.          ///這裏只是測試,您可以根據實際的文件類型進行動態輸出
  95.          return "image/jpg";
  96.         }
  97.       }
  98.     }
  99.     }

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

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

  1. using System;
  2.     using System.Collections;
  3.     using System.ComponentModel;
  4.     using System.Data;
  5.     using System.Drawing;
  6.     using System.Web;
  7.     using System.Web.SessionState;
  8.     using System.Web.UI;
  9.     using System.Web.UI.WebControls;
  10.     using System.Web.UI.HtmlControls;
  11.     using System.Web.Services;
  12.     namespace aspxWebCS
  13.     {
  14.         /// <summary>
  15.         /// GetBinaryFileShow 的摘要說明。
  16.         /// </summary>
  17.         public class GetBinaryFileShow : System.Web.UI.Page
  18.         {
  19.             private void Page_Load(object sender, System.EventArgs e)
  20.             {
  21.             // 在此處放置用戶代碼以初始化頁面
  22.            ///定義並初始化文件對象;
  23.            xml.sz.luohuedu.net.aspxWebCS.GetBinaryFile.Images oImage;
  24.            oImage = new xml.sz.luohuedu.net.aspxWebCS.GetBinaryFile.Images();
  25.            ///得到二進制文件字節數組;
  26.            byte[] image = oImage.GetImage("");
  27.            ///轉換爲支持存儲區爲內存的流
  28.            System.IO.MemoryStream memStream = new System.IO.MemoryStream(image);
  29.            ///定義並實例化Bitmap對象
  30.            Bitmap bm = new Bitmap(memStream);
  31.            ///根據不同的條件進行輸出或者下載;
  32.            Response.Clear();
  33.            ///如果請求字符串指定下載,就下載該文件;
  34.            ///否則,就顯示在瀏覽器中。
  35.            if(Request.QueryString["Download"]=="1")
  36.            {
  37.             Response.Buffer = true;
  38.             Response.ContentType = "application/octet-stream";
  39.             ///這裏下載輸出的文件名字 ok.jpg 爲例子,你實際中可以根據情況動態決定。
  40.             Response.AddHeader("Content-Disposition","attachment;filename=ok.jpg");
  41.            }
  42.            else
  43.             Response.ContentType = oImage.GetImageType();
  44.            Response.BinaryWrite(image);
  45.            Response.End();
  46.             }
  47.             #region Web Form Designer generated code
  48.             override protected void OnInit(EventArgs e)
  49.             {
  50.                 //
  51.                 // CODEGEN:該調用是 ASP.NET Web 窗體設計器所必需的。
  52.                 //
  53.                 InitializeComponent();
  54.                 base.OnInit(e);
  55.             }
  56.             /// <summary>
  57.             /// 設計器支持所需的方法 - 不要使用代碼編輯器修改
  58.             /// 此方法的內容。
  59.             /// </summary>
  60.             private void InitializeComponent()
  61.             {
  62.        this.Load += new System.EventHandler(this.Page_Load);
  63.       }
  64.             #endregion
  65.         }
  66.     }

 

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

 

  1. <%@ Page language="c#" Codebehind="GetBinaryFile.aspx.cs" AutoEventWireup="false"
  2.       Inherits="aspxWebCS.GetBinaryFile" %>
  3.     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
  4.     <HTML>
  5.       <HEAD>
  6.         <title>通過Web Services顯示和下載文件</title>
  7.         <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
  8.         <meta name="CODE_LANGUAGE" Content="C#">
  9.         <meta name="vs_defaultClientScript" content="JavaScript">
  10.         <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  11.       </HEAD>
  12.       <body MS_POSITIONING="GridLayout">
  13.         <form id="GetBinaryFile" method="post" runat="server">
  14.           <FONT face="宋體">
  15.             <asp:HyperLink id="HyperLink1" NavigateUrl="GetBinaryFileShow.aspx?Download=1"
  16.              runat="server">下載文件</asp:HyperLink>
  17.             <br/>
  18.             <!--下面是直接顯示文件-->
  19.             <asp:Image id="Image1" ImageUrl="GetBinaryFileShow.aspx" runat="server"></asp:Image>
  20.           </FONT>
  21.         </form>
  22.       </body>
  23.     </HTML>

 

二:通過Web Services上載文件

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

  1. using System;
  2.     using System.Collections;
  3.     using System.ComponentModel;
  4.     using System.Data;
  5.     using System.Diagnostics;
  6.     using System.Web;
  7.     using System.Web.Services;
  8.     using System.IO;
  9.     namespace xml.sz.luohuedu.net.aspxWebCS
  10.     {
  11.         /// <summary>
  12.         /// Upload 的摘要說明。
  13.         /// </summary>
  14.      [WebService(Namespace="http://xml.sz.luohuedu.net/",
  15.         Description="在Web Services裏利用.NET框架進上載文件。")]
  16.         public class Upload : System.Web.Services.WebService
  17.         {
  18.             public Upload()
  19.             {
  20.                 //CODEGEN:該調用是 ASP.NET Web 服務設計器所必需的
  21.                 InitializeComponent();
  22.             }
  23.             #region Component Designer generated code
  24.             //Web 服務設計器所必需的
  25.             private IContainer components = null;
  26.             /// <summary>
  27.             /// 設計器支持所需的方法 - 不要使用代碼編輯器修改
  28.             /// 此方法的內容。
  29.             /// </summary>
  30.             private void InitializeComponent()
  31.             {
  32.             }
  33.             /// <summary>
  34.             /// 清理所有正在使用的資源。
  35.             /// </summary>
  36.             protected override void Dispose( bool disposing )
  37.             {
  38.                 if(disposing && components != null)
  39.                 {
  40.                     components.Dispose();
  41.                 }
  42.                 base.Dispose(disposing);
  43.             }
  44.             #endregion
  45.       [WebMethod(Description="Web 服務提供的方法,返回是否文件上載成功與否。")]
  46.       public string UploadFile(byte[] fs,string FileName)
  47.       {
  48.        try
  49.        {
  50.         ///定義並實例化一個內存流,以存放提交上來的字節數組。
  51.         MemoryStream m = new MemoryStream(fs);
  52.         ///定義實際文件對象,保存上載的文件。
  53.         FileStream f = new FileStream(Server.MapPath(".") + "//"
  54.          + FileName, FileMode.Create);
  55.         ///把內內存裏的數據寫入物理文件
  56.         m.WriteTo(f);
  57.         m.Close();
  58.         f.Close();
  59.         f = null;
  60.         m = null;
  61.         return "文件已經上傳成功。";
  62.        }
  63.        catch(Exception ex)
  64.        {
  65.         return ex.Message;
  66.        }
  67.       }
  68.     }
  69.     }

 

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

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

 

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

  1. using System;
  2.     using System.Collections;
  3.     using System.ComponentModel;
  4.     using System.Data;
  5.     using System.Drawing;
  6.     using System.Web;
  7.     using System.Web.SessionState;
  8.     using System.Web.UI;
  9.     using System.Web.UI.WebControls;
  10.     using System.Web.UI.HtmlControls;
  11.     using System.Web.Services;
  12.     using System.IO;
  13.     namespace aspxWebCS
  14.     {
  15.         /// <summary>
  16.         /// Upload 的摘要說明。
  17.         /// 利用該方法通過Web Services上載文件
  18.         /// </summary>
  19.         public class Upload : System.Web.UI.Page
  20.         {
  21.       protected System.Web.UI.HtmlControls.HtmlInputFile MyFile;
  22.       protected System.Web.UI.WebControls.Button Button1;
  23.             private void Page_Load(object sender, System.EventArgs e)
  24.             {
  25.                 // 在此處放置用戶代碼以初始化頁面
  26.             }
  27.             #region Web Form Designer generated code
  28.             override protected void OnInit(EventArgs e)
  29.             {
  30.                 //
  31.                 // CODEGEN:該調用是 ASP.NET Web 窗體設計器所必需的。
  32.                 //
  33.                 InitializeComponent();
  34.                 base.OnInit(e);
  35.             }
  36.             /// <summary>
  37.             /// 設計器支持所需的方法 - 不要使用代碼編輯器修改
  38.             /// 此方法的內容。
  39.             /// </summary>
  40.             private void InitializeComponent()
  41.             {
  42.        this.Button1.Click += new System.EventHandler(this.Button1_Click);
  43.        this.Load += new System.EventHandler(this.Page_Load);
  44.       }
  45.             #endregion
  46.       private void Button1_Click(object sender, System.EventArgs e)
  47.       {
  48.        ///首先得到上載文件信息和文件流
  49.        if(MyFile.PostedFile != null)
  50.        {
  51.         System.Web.HttpFileCollection oFiles;
  52.         oFiles = System.Web.HttpContext.Current.Request.Files;
  53.         if(oFiles.Count < 1)
  54.         {
  55.          Response.Write ("請選擇文件。");
  56.          Response.End();
  57.         }
  58.         string FilePath = oFiles[0].FileName;
  59.         if(FilePath == "" || FilePath == null)
  60.         {
  61.          Response.Write ("請選擇一個文件。");
  62.          Response.End();
  63.         }
  64.         string FileName = FilePath.Substring(FilePath.LastIndexOf("//")+1);
  65.         try
  66.         {
  67.          ///處理上載的文件流信息。
  68.          byte[] b = new byte[oFiles[0].ContentLength];
  69.          System.IO.Stream fs;
  70.          xml.sz.luohuedu.net.aspxWebCS.Upload o;
  71.          o = new xml.sz.luohuedu.net.aspxWebCS.Upload();
  72.          fs = (System.IO.Stream)oFiles[0].InputStream;
  73.          fs.Read(b, 0, oFiles[0].ContentLength);
  74.          ///調用Web Services的UploadFile方法進行上載文件。
  75.          Response.Write(o.UploadFile(b, FileName));
  76.          fs.Close();
  77.         }
  78.         catch(Exception ex)
  79.         {
  80.          Response.Write(ex.Message);
  81.         }
  82.        }
  83.        else
  84.        {
  85.         Response.Write("請選擇文件");
  86.     }
  87.    }
  88.   }
  89.  }

 

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

其中: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 屬性的值。例如:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章