概述
我們知道,在Silverlight 2中提供了豐富的網路通訊API,包括支援SOAP服 務、REST服務、基於HTTP通訊、Socket通訊等。本文我將通過幾個樣本來示範如 何在Silverlight 2中應用Web Service實現檔案上傳和電子郵件發送。
使用Web Service上傳檔案
我將通過一個樣本來展示如何使用Web Service向伺服器上傳檔案,首先建立 Silverlight項目,並在Web測試專案中添加一個ASP.NET Web Service檔案。現 在來實現相關的WebMethod,在此方法中,將會接收兩個參數:位元組數組和檔案 副檔名,並會在伺服器上建立檔案,如下代碼所示:
public class FileService : WebService
{
[WebMethod]
public int UploadFile(byte[] FileByte, String FileExtention)
{
FileStream stream = new FileStream(String.Format(@"D:\example.{0}", FileExtention),FileMode.CreateNew);
stream.Write(FileByte, 0, FileByte.Length);
stream.Close();
return FileByte.Length;
}
}
添加一個簡單的介面,供使用者選擇本地檔案,我們將在按鈕單擊單擊事件中 調用Web Service,如下代碼所示:
<Canvas Background="#FF333333">
<TextBox x:Name="txtFile" Height="30" Width="300" Canvas.Top="120"
Canvas.Left="30" Style="{StaticResource textBoxStyle}"></TextBox>
<Button x:Name="btnUpload" Width="60" Content="上 傳" Height="30"
Canvas.Left="340" Canvas.Top="120" Style="{StaticResource buttonStyle}"
Click="OnUploadClick"></Button>
<TextBlock x:Name="tblStatus" Canvas.Left="30" Canvas.Top="160"
FontSize="14" Foreground="White" Text=""></TextBlock>
</Canvas>