本文标签:Web Service上传文件 ASP.NET
我们知道,在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="上传文件成功!";
- }
- }
|