發表日期:23/04/2002 14:43:09
發表人:Robert Chartier
發表人信箱:[email protected]
本文說明如何創建和使用二進制數據傳送的Web服務,這是相當容易的一件事。
=================================================================
在示例中,將從本地磁盤取出圖象數據,然後使用SOAP信息將圖象傳送到調用者手上。
現在開始討論有關的Web服務,並特別注重數據編碼的有關操作。
0. [WebMethod(Description="Get an Image using Base64 Encoding")]
1. public byte[] GetImage() {
2. return getBinaryFile("C://Inetpub//wwwroot//webservices//public//images//logo.gif");
3. }
4.
注意函數返回byte[] (字節數組)。.NET將自動將返回的數據編碼成爲base64格式。
下面的"getBinaryFile()"函數用文件流從硬盤讀取文件,然後將圖象文件數據轉換爲byte[]:
0. public byte[] getBinaryFile(string filename) {
1. if(File.Exists(filename)) {
2. try {
3. FileStream s=File.OpenRead(filename);
4. return ConvertStreamToByteBuffer(s);
5. }
catch(Exception e) {
6. return new byte[0];
7. }
8. }
else {
9. return new byte[0];
10. }
11. }
12.
13. public byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream) {
14. int b1;
15. System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
16. while((b1=theStream.ReadByte())!=-1) {
17. tempStream.WriteByte(((byte)b1));
18. }
19. return tempStream.ToArray();
20. }
現在可以在.NET上用C#編寫客戶端程序,過程如下:
1. 創建C#應用窗體
2. 增加一個Picture Box控件,命名爲pct1
3. 增加一個Web引用(Reference)到:http://rob.santra.com/webservices/public/images/index.asmx?wsdl
4. 在程序的事件驅動(Form1_Load, 或其它事件)中寫入以下代碼:
0. com.santra.rob.Images images = new com.santra.rob.Images();
1. byte[] image = images.GetImage();
2. System.IO.MemoryStream memStream = new System.IO.MemoryStream(image);
3. Bitmap bm = new Bitmap(memStream);
4. pct1.Image = bm;
5.
6.
如果是在自己的服務器上創建這種服務,就要改變Web Reference(引用)地址,同時com.santra.rob.Images()對象也要與增加Web Reference(引用)時創建的對象相一致。
在上面的代碼中,客戶向服務器申請含有圖象數據的字節數組,並將該數組轉換到內存流(MemoryStream),然後加載到Bitmap對象,最後用pct1圖象控件顯示得到的圖象。
整個過程就是這麼簡單!
以下是全部代碼:
0. <%@ Webservice Language="C#" class="Images" %>
1.
2. using System;
3. using System.Web.Services;
4. using System.IO;
5.
6. [WebService(Namespace="http://rob.santra.com/webservices/public/images/", Description="Demonstration of using Base64 encoding, in a Web Service using the .NET Framework.")]
7. public class Images: System.Web.Services.WebService {
8. [WebMethod(Description="Get an Image using Base64 Encoding")]
9. public byte[] GetImage() {
10. return getBinaryFile("C://Inetpub//wwwroot//webservices//public//images//logo.gif");
11. }
12. public byte[] getBinaryFile(string filename) {
13. if(File.Exists(filename)) {
14. try {
15. FileStream s=File.OpenRead(filename);
16. return ConvertStreamToByteBuffer(s);
17. }
catch(Exception e) {
18. return new byte[0];
19. }
20. }
else {
21. return new byte[0];
22. }
23. }
24.
25. public byte[] ConvertStreamToByteBuffer(System.IO.Stream theStream) {
26. int b1;
27. System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
28. while((b1=theStream.ReadByte())!=-1) {
29. tempStream.WriteByte(((byte)b1));
30. }
31. return tempStream.ToArray();
32. }
33. }