ASP.NET使用Web Service上傳文件
我們知道,在Silverlight 2中提供了豐富的網絡通信API,包括支持SOAP服務、REST服務、基于HTTP通信、Socket通信等。本文我將通過一個幾個示例來演示如何在Silverlight 2中實現文件上傳和電子郵件發送。
ASP.NET使用Web Service上傳文件
我將通過一個示例來展示如何使用Web Service上傳文件,首先創建Silverlight項目,并在Web測試項目中添加一個ASP.NET Web Service文件。現在來實現相關的WebMethod,在此方法中,將會接收兩個參數:字節數組和文件擴展名,并會在服務器上創建文件,如下代碼所示:
- 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;
- }
添加一個簡單的界面,供用戶選擇本地文件,我們將在按鈕單擊單擊事件中調用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調用Web Service上傳文件,此處使用了OpenFileDialog對象彈出擇窗口以便選擇文件,此對象將選擇的文件作為Stream返回,我們把Stream轉換為一個字節數據傳遞給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="上傳文件成功!";
- }
- }
【編輯推薦】