Progress Indication while Uploading/Downloading Files using WCF(WCF制作带进度条的上传/下载)(转载)
2011-11-11 16:41
92 查看
Download source files - 86.17 KB
The sample code consists of three projects bundled in a solution. A brief description of these projects follows. The attached sample code is available in C# and VB.NET (conversion to VB.NET was made by Lee Galloway of Project Time and Cost).
Collapse | Copy Code
Collapse | Copy Code
Note here that since actual downloading of the file starts after the execution of the
Collapse | Copy Code
Collapse | Copy Code
The configuration of
Collapse | Copy Code
Again, if you have worked with streams before, you will notice that things are pretty simple in the TestForm file except for one small part, which is also the difference in implementing the progress indication when uploading rather than when downloading. When downloading, the client has control of the procedure. You can see in TestForm.cs that downloading is implemented using a loop that reads the server stream piece-by-piece. So, the client knows what part of the server stream is read and how many more remain. When uploading, that loop resides on the server. In order for the client to know how many bytes the server read, it uses the
Collapse | Copy Code
Collapse | Copy Code
Updated on 2007/10/24: Code now also provided in VB.NET. Conversion made by Lee Galloway of Project Time and Cost.
Updated on 2009/02/03:
Upgraded projects to Visual Studio 2008 (.NET Framework 2.0 is still the target framework).
Properly closing read stream on client when download is done. Failure to do this was causing the client to throw timeout exceptions after 2 or 3 downloads.
原文地址(http://www.codeproject.com/KB/WCF/WCF_FileTransfer_Progress.aspx)
Introduction
This article examines the implementation of upload and download functionality with progress indication (progress bar feature) using the Windows Communication Foundation. For this sample, you will need Visual Studio 2008.The sample code consists of three projects bundled in a solution. A brief description of these projects follows. The attached sample code is available in C# and VB.NET (conversion to VB.NET was made by Lee Galloway of Project Time and Cost).
FileService
This is the main server project.The Server Contract
The File Server project includes FileTransferServiceContract.cs file, which contains theIFileTransferServiceinterface. This interface describes the operations provided by our server. No actual work is done in this code file except in describing the operations provided. If you've worked with service-oriented applications before, you'll know that this job is important enough to spare a separate file for. Here are the two operations of our file transfer service:
DownloadFile Server Method
Accepts aDownloadRequestinstance that contains the name of the file to be downloaded by the client. It returns a
RemoteFileInfoinstance, defined in the same code file.
RemoteFileInfocontains the name of the file to be downloaded, the file stream and the length of the file in bytes. This instance of the
RemoteFileInfoclass will be used by the client to download the file. You notice that
filenameand
lengthare marked with the
MessageHeaderattribute in the
RemoteFileInfoclass. This is because when a message contract contains a
stream, this can be the only body member of the contract.
UploadFile Server Method
Accepts an instance of theRemoteFileInfomessage contract. This is the same as used in
DownloadFile, only in this case the
lengthproperty is not required.
CS
Collapse | Copy Code
[ServiceContract()] public interface IFileTransferService { [OperationContract()] void UploadFile(RemoteFileInfo request); [OperationContract] RemoteFileInfo DownloadFile(DownloadRequest request); } public class RemoteFileInfo { [MessageHeader(MustUnderstand = true)] public string FileName; [MessageHeader(MustUnderstand = true)] public long Length; [MessageBodyMember(Order = 1)] public System.IO.Stream FileByteStream; }
VB
Collapse | Copy Code
<ServiceContract()> _ <servicecontract() />Public Interface IFileTransferService <OperationContract()> _ Sub UploadFile(ByVal request As RemoteFileInfo) <OperationContract()> _ Function DownloadFile(ByVal request As DownloadRequest) As RemoteFileInfo End Interface <MessageContract()> _ Public Class RemoteFileInfo Implements IDisposable <OperationContract()> _ Public FileName As String <OperationContract()> _ Public Length As Long <MessageBodyMember(Order:=1)> _ Public FileByteStream As System.IO.Stream End Class
The Server Implementation
File Server also includes the FileTransferService.cs code file which contains the implementation of the contract, i.e. the actual code that does all the work. Apparently the included class implements theIFileTransferServiceclass, which constitutes the service contract. If you have worked with streams before in .NET, you will find out that the code that handles the stream and related information for upload or download is pretty straightforward. If you are new to .NET streams, please use Google for a quick introduction.
Note here that since actual downloading of the file starts after the execution of the
DownloadFilemethod is completed (i.e. after the client gets the
RemoteFileInfoinstance returned by this method), the server must close the opened stream later, after the client completes the process. An elegant approach was suggested by Buddhike. To do this, the
IDisposableinterface is implemented by the
RemoteFileInfocontract and the stream is disposed on the corresponding
Disposemethod. If this is not done, the stream will remain locked and the corresponding file will be locked for writing.
ConsoleHost
FileServiceis a class library and hence it cannot start as a window process. Therefore it needs another executable file-process that will host it. Several types of processes can host a WCF service, such as .NET executables, IIS processes, Windows Activation Services (new feature of Vista) and many more. Our example uses a .NET executable to host our service. So,
ConsoleHostis a console application that does exactly this. It has a reference to the
FileServiceproject. However, it is not related in any way with the business our service is doing, i.e. transferring files. Actually, the code you will find in Program.cs would be the same even if our service was designed to host an online grocery. Take a quick look at this code file to understand how our service is started and closed.
CS
Collapse | Copy Code
static void Main(string[] args) { ServiceHost myServiceHost = new ServiceHost (typeof(FileService.FileTransferService)); myServiceHost.Open(); Console.WriteLine("This is the SERVER console"); Console.WriteLine("Service Started!"); foreach (Uri address in myServiceHost.BaseAddresses) Console.WriteLine("Listening on " + address.ToString()); Console.WriteLine("Click any key to close..."); Console.ReadKey(); myServiceHost.Close(); }
VB
Collapse | Copy Code
Public Shared Sub Main() Dim myServiceHost As New ServiceHost(_ GetType(FileService.FileTransferService)) myServiceHost.Open() Console.WriteLine("This is the SERVER console") Console.WriteLine("Service Started!") For Each address As Uri In myServiceHost.BaseAddresses Console.WriteLine("Listening on " + address.ToString()) Next Console.WriteLine("Click any key to close...") Console.ReadKey() myServiceHost.Close() End Sub
The configuration of
ConsoleHostis what matters the most! It is divided into three sections, configuring the way our service will behave and how it will be exposed to the rest of the world. It is not the goal of this article to describe in detail how a WCF service is configured, so please refer to the WCF reference on MSDN for more information. Something noticeable in the configuration of our service is that it uses
MTOMas message encoding and stream as transfer mode. See also the
maxReceivedMessageSizeproperty. This defines the maximum size of messages transferred by our service. Since we are transferring files, we want this property to have a large value.
XML
Collapse | Copy Code
<binding name ="FileTransferServicesBinding" transferMode="Streamed" messageEncoding="Mtom" maxReceivedMessageSize="10067108864" > </binding>
Client
TheClientproject is a sample consumer of our service. You will notice that the
Clientproject includes a folder called Service References. This folder contains a bunch of files created automatically by Visual Studio by right clicking on the
Clientproject root and selecting "Add Service Reference." The files in this folder are the proxy of our file transfer service on the client side.
Clientis using these files to send requests to the server, hiding in this way the complexity of Web Service and SOAP protocols.
Again, if you have worked with streams before, you will notice that things are pretty simple in the TestForm file except for one small part, which is also the difference in implementing the progress indication when uploading rather than when downloading. When downloading, the client has control of the procedure. You can see in TestForm.cs that downloading is implemented using a loop that reads the server stream piece-by-piece. So, the client knows what part of the server stream is read and how many more remain. When uploading, that loop resides on the server. In order for the client to know how many bytes the server read, it uses the
StreamWithProgressclass, which inherits
System.IO.Stream. An instance of this class is passed to the server, instead of the original file stream. Since this class overrides the default
Readmethod of the stream (see code below), it can report the progress of the uploading process to the client!
CS
Collapse | Copy Code
public override int Read(byte[] buffer, int offset, int count) { int result = file.Read(buffer, offset, count); bytesRead += result; if (ProgressChanged != null) ProgressChanged(this, new ProgressChangedEventArgs(bytesRead, length)); return result; }
VB
Collapse | Copy Code
Public Overloads Overrides Function Read(ByVal buffer As Byte(), _ ByVal offset As Integer, ByVal count As Integer) As Integer Dim result As Integer = file.Read(buffer, offset, count) bytesRead += result RaiseEvent ProgressChanged(Me, New ProgressChangedEventArgs(_ bytesRead, m_length)) Return result End Function
History
Updated on 2007/09/09: A more elegant approach for the server implementation was suggested by Buddhike.Updated on 2007/10/24: Code now also provided in VB.NET. Conversion made by Lee Galloway of Project Time and Cost.
Updated on 2009/02/03:
Upgraded projects to Visual Studio 2008 (.NET Framework 2.0 is still the target framework).
Properly closing read stream on client when download is done. Failure to do this was causing the client to throw timeout exceptions after 2 or 3 downloads.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)原文地址(http://www.codeproject.com/KB/WCF/WCF_FileTransfer_Progress.aspx)
相关文章推荐
- Yii使用ajax上传文件 EAjaxUpload: Uploading files using ajax (without flash)
- [DeploymentService:290066]Error occurred while downloading files from admin server for deployment re
- Uploading and Downloading Files
- [转帖]An Insider View of Uploading Files using ASP
- Downloading files in Flex using the FileReference class
- ADF Single/Multiple files uploading and downloading 在
- Uploading files in Flex using the FileReference class
- weblogic部署问题,Exception occured while downloading files,Error Comments may not contain '--'
- Uploading Files Using the File Field Control (ASP.NET上传文件)(zz)
- [转载]Step By Step - Using Silverlight to Access a WCF Service Hosted In a Console Application
- Uploading files using ASP.NET Web Api
- Using the command line to manage files on HDFS--转载
- Downloading files from a server to client, using ASP.Net, when file size is too big for MemoryStream using Generic Handlers (ashx)
- ASP.NET MVC Uploading and Downloading Files
- [转载]解决VMware Tools installation cannot be started manually while Easy Install is in progress
- 【转载】在ASP.NET 2.0 中如何使用多个Sitemap文件【Using Multiple Sitemap Files in ASP.NET 2.0--英文】
- Uploading Files in ASP.NET 2.0[转载】
- Error occurred while downloading files from Administration Server for deployment request
- Using #region Directive With JavaScript Files in Visual Studio 【转载】
- ASP.NET MVC Uploading and Downloading Files