Pages

Friday, August 3, 2012

Upload files using a WCF REST Service


Upload files using a WCF REST Service

A WCF REST Service that allows to upload (and download) images to (and from) a remote server. Images are stored in a SQL Server Compact 4.0 database. The service exposes also a method to obtain the list of all images, along with their name and description, and a method to delete an image.

Building the Sample

The code you can download from this page contains the WCF REST Service, named PhotoService, and a WPF Application, PhotoServiceClient, that shows how to call its methods. Inside the ZIP file you'll find a single Solution that includes both the service and the client.
To debug these projects, first right click on PhotoService in the Solution Explorer, then select the Debug | Start new instance command from the context menu. Repeat this action for the PhotoServiceClient. In this way, you can execute both the service and the client within the same instance of Visual Studio and, of course, you can insert breakpoints in any point of the code.
Ensure that, in the project properties of PhotoService, under the Web tag, the Specific port radio button is checked. You might modify the app.config file in the PhotoServiceClient project to set the correct URL for the service in the ServiceUrl tag.

Description

The WCF REST Service has been created using the WCF REST Service Template 40 (CS). It simplifies a lot the process of creating the service files and making the right configuration in web.config. Working with this file, in fact, can be quite difficult, but this template creates a basic configuration that is perfect to start with.
One of the most important settings that must be adjust in the web.config file regards the standardEnpoint tag. To make the service accept large files upload, you must add a maxReceivedMessageSize attribute, that specifies the maximun length, in bytes, of a message that can be sent by a client. In the PhotoService service, this tag is set to 4 MB.
Once uploaded, the files are saved in a SQL Server Compact 4.0, that is accessed using ADO .NET Entity Framework via an Entity Data Model.
After you have started the debug of the service, you can see all the methods that are exposed, along with input parameters and example of return messages, visiting the page http://localhost:<port_number>/photos/help.
Using the service is straightforward. You can use make a standard HttpWebRequest to invoke its methods. For example, see the following code, taken from the PhotoServiceClient, to upload the specified image to the server:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl); 
request.Method = "POST"; 
request.ContentType = "text/plain"; 
 
byte[] fileToSend = File.ReadAllBytes(txtFileName.Text);  // txtFileName contains the name of the file to upload. 
request.ContentLength = fileToSend.Length; 
 
using (Stream requestStream = request.GetRequestStream()) 
{ 
    // Send the file as body request. 
    requestStream.Write(fileToSend, 0, fileToSend.Length); 
    requestStream.Close(); 
} 
 
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
    Console.WriteLine("HTTP/{0} {1} {2}", response.ProtocolVersion, (int)response.StatusCode, response.StatusDescription);
And this is the code to download the image with ID 123 and save it in a BitmapImage object:
// Create the REST request. 
string url = ConfigurationManager.AppSettings["serviceUrl"]; 
string requestUrl = string.Format("{0}/GetPhoto/123"); 
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl); 
 
// Get response   
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) 
{ 
    using (Stream stream = response.GetResponseStream()) 
    { 
        byte[] buffer = new byte[32768]; 
        MemoryStream ms = new MemoryStream(); 
        int bytesRead, totalBytesRead = 0; 
        do 
        { 
            bytesRead = stream.Read(buffer, 0, buffer.Length); 
            totalBytesRead += bytesRead; 
 
            ms.Write(buffer, 0, bytesRead); 
        } while (bytesRead > 0); 
 
        ms.Position = 0; 
        BitmapImage bmp = new BitmapImage(); 
        bmp.BeginInit(); 
        bmp.StreamSource = ms; 
        bmp.EndInit(); 
 
        imgPhoto.Source = bmp; 
    } 
}
As the service works with standard REST calls, if you prefer you can also use a third-party library to communicate with it. For example, you can refert to RestSharp, that is available at http://restsharp.org.
Finally, notice that this example allows to upload, manage and download JPEG, GIF, BMP and PNG images, but the code can be easily adapted to support any file type.

More Information

No comments:

Post a Comment