JSON Web Service Image File Upload

Web.Config Settings:

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

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
        <standardEndpoint name="Default" helpEnabled="true" maxBufferSize="33554432" maxReceivedMessageSize="33554432" transferMode="Streamed" automaticFormatSelectionEnabled="false"/>

In Global.asax.cs add:

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

Web Service class:

	[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;
				bytesRead = image.Read(buffer, 0, buffer.Length);
				dbStream.Write(buffer, 0, bytesRead);
			} while (bytesRead > 0);

Use Fiddler2 to test service:

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
%d bloggers like this: