Anthony Johnston Anthony Johnston - 1 year ago 241
HTTP Question

WCF service to accept a post encoded multipart/form-data

Does anyone know, or better yet have an example, of a WCF service that will accept a form post encoded

ie. a file upload from a web page?

I have come up empty on google.

Ta, Ant

Answer Source

So, here goes...

Create your service contract which an operation which accepts a stream for its only parameter, decorate with WebInvoke as below

public interface IService1 {

        Method = "POST",
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "/Upload")]
    void Upload(Stream data);


Create the class...

    public class Service1 : IService1 {

    public void Upload(Stream data) {

        // Get header info from WebOperationContext.Current.IncomingRequest.Headers
        // open and decode the multipart data, save to the desired place

And the config, to accept streamed data, and the maximum size

       <binding name="WebConfiguration" 
       <behavior name="WebBehavior">
         <webHttp />         
       <behavior name="Sandbox.WCFUpload.Web.Service1Behavior">
         <serviceMetadata httpGetEnabled="true" httpGetUrl="" />
         <serviceDebug includeExceptionDetailInFaults="false" />
     <service name="Sandbox.WCFUpload.Web.Service1" behaviorConfiguration="Sandbox.WCFUpload.Web.Service1Behavior">
        contract="Sandbox.WCFUpload.Web.IService1" />

Also in the System.Web increase the amount of data allowed in System.Web

        <httpRuntime maxRequestLength="2000000"/>

This is just the basics, but allows for the addition of a Progress method to show an ajax progress bar and you may want to add some security.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download