JSON Web Service Image File Upload


Web.Config Settings:

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </modules>
  </system.webServer>

  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint name="Default" helpEnabled="true" maxBufferSize="33554432" maxReceivedMessageSize="33554432" transferMode="Streamed" automaticFormatSelectionEnabled="false"/>
      </webHttpEndpoint>
    </standardEndpoints>
  </system.serviceModel>

In Global.asax.cs add:

  RouteTable.Routes.Add(new ServiceRoute("images", new WebServiceHostFactory(), typeof(ServicesMgr)));

Web Service class:

	[ServiceContract]
	[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
	[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
	public class ServicesMgr
	{
		[WebInvoke(UriTemplate = "/upload.json?guid={guid}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
		public void Upload(string guid, Stream image)
		{
			if (string.IsNullOrWhiteSpace(guid))
				throw new WebFaultException<string>("Parameter guid is null", System.Net.HttpStatusCode.BadRequest);
			
			// Write image to backend repository
			byte[] buffer = new byte[32768];
			int bytesRead = 0;
			do
			{
				bytesRead = image.Read(buffer, 0, buffer.Length);
				dbStream.Write(buffer, 0, bytesRead);
			} while (bytesRead > 0);
		}
	}

Use Fiddler2 to test service:
Fiddler2

Posted in WCF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Antek Group Blog
Categories
%d bloggers like this: