ASP.NET使用Web Service上傳文件
我們知道,在Silverlight 2中提供了豐富的網(wǎng)絡(luò)通信API,包括支持SOAP服務(wù)、REST服務(wù)、基于HTTP通信、Socket通信等。本文我將通過一個幾個示例來演示如何在Silverlight 2中實(shí)現(xiàn)文件上傳和電子郵件發(fā)送。
ASP.NET使用Web Service上傳文件
我將通過一個示例來展示如何使用Web Service上傳文件,首先創(chuàng)建Silverlight項(xiàng)目,并在Web測試項(xiàng)目中添加一個ASP.NET Web Service文件?,F(xiàn)在來實(shí)現(xiàn)相關(guān)的WebMethod,在此方法中,將會接收兩個參數(shù):字節(jié)數(shù)組和文件擴(kuò)展名,并會在服務(wù)器上創(chuàng)建文件,如下代碼所示:
- C#
 - [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;
 - }
 
添加一個簡單的界面,供用戶選擇本地文件,我們將在按鈕單擊單擊事件中調(diào)用Web Service,如下代碼所示:
XAML 
- <Canvas Background="#FF333333">
 - <TextBox x:Name="txtFile"></TextBox>
 - <Button x:Name="btnUpload" Click="OnUploadClick"></Button>
 - <TextBlock x:Name="tblStatus"></TextBlock>
 - </Canvas>
 
ASP.NET調(diào)用Web Service上傳文件,此處使用了OpenFileDialog對象彈出擇窗口以便選擇文件,此對象將選擇的文件作為Stream返回,我們把Stream轉(zhuǎn)換為一個字節(jié)數(shù)據(jù)傳遞給Web Service,如下代碼所示:
- voidOnUploadClick(objectsender,RoutedEventArgse)
 - {
 - OpenFileDialogopenFile=newOpenFileDialog();
 - if(openFile.ShowDialog()==DialogResult.OK)
 - {
 - StringfileName=openFile.SelectedFile.Name;
 - FileServiceSoapClientclient=newFileServiceSoapClient();
 - client.UploadFileCompleted+=newEventHandler<UploadFileCompletedEventArgs>
 
(OnUploadFileCompleted);- Streamstream=(Stream)openFile.SelectedFile.OpenRead();
 - stream.Position=0;
 - byte[]buffer=newbyte[stream.Length+1];
 - stream.Read(buffer,0,buffer.Length);
 - StringfileExtention=fileName.Substring(fileName.IndexOf('.')+1);
 - client.UploadFileAsync(buffer,fileExtention);
 - }
 - }
 - voidOnUploadFileCompleted(objectsender,UploadFileCompletedEventArgse)
 - {
 - if(e.Error==null)
 - {
 - tblStatus.Text="上傳文件成功!";
 - }
 - }
 
【編輯推薦】















 
 
 
 
 
 
 