Uploading File using WCF service

A sample code Uploading File using WCF RESTFUL service with MVC is explained in this article.

1. Open Visual Studio -> Click on File Menu-> New Project -> Name your Project & Set the Location of your Project -> Click Ok. I have named the project as  “FileWorker“.
2. In Next Screen obviously you have to select “Internet Application“.
3. Right click on the Project and Add New Item WCF service and Name your service as “FileService.svc“.  It will create two files “FileService.svc” and “IFileService.cs“.
4.  Open the  FileService.svc and Paste the below Code:
Also Right Click on the project and add the Folders. Files and sub folder folder “Uploads” where all the uploaded files will be saved in the location.

public class FileService : IFileService
    {       

        public void UploadFile(string fileName, Stream stream)
        {
            try
            {
                string FilePath = Path.Combine(HostingEnvironment.MapPath("~/Files/Uploads"), fileName);

                int length = 0;
                using (FileStream writer = new FileStream(FilePath, FileMode.Create))
                {
                    int readCount;
                    var buffer = new byte[8192];
                    while ((readCount = stream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        writer.Write(buffer, 0, readCount);
                        length += readCount;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }

5. Add beow piece of code in IFileService.cs file.

[ServiceContract]
   public interface IFileService
   {
       [OperationContract]
       [WebInvoke(Method = "POST", UriTemplate = "/UploadFile?fileName={fileName}")]
       void UploadFile(string fileName, Stream stream);
   }

6. Open the Index,cshtml file, under the Views -> Home folder inside the project. And Paste the below code in it.

<div>
    <form id="frm" runat="server">
        <div>
            <input type="file" id="fileUpload" value="" />
            <button type="button" id="btnUpload">Upload</button>
        </div>
    </form>
</div>

<script type="text/javascript">
    $(document).ready(function () {

        // Note: Change the port number(localhost:60418) according to yours (if  modified).

        // Upload Button Click
        $("#btnUpload").click(function () {
            var data = new FormData();
            fileData = document.getElementById("fileUpload").files[0];

            $.ajax({
                url: 'http://localhost:53333/FileService.svc/UploadFile?fileName=' + fileData.name, // Dynamically uploads the files which is chosen.
                type: 'POST',
                data: fileData, // This would pass the file object with data
                cache: false,
                processData: false, // Don't process the files
                contentType: "application/octet-stream", // Setting content type to "application/octet-stream" as jQuery will tell the server its not query string. 
                success: function (data) {
                    alert('Successful..');
                },
                error: function (data) {
                    alert('Error Occurred');
                }
            });
        });       
    });
</script>

7. Add below configurations in web.config file.

<system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="FileWorker.webHttpBinding" transferMode="Streamed">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
        </binding>
      </webHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="FileWorker.ServiceBehaviour" name="FileWorker.FileService">
        <endpoint address="" behaviorConfiguration="FileWebEndPoint" binding="webHttpBinding" bindingConfiguration="FileWorker.webHttpBinding" contract="FileWorker.IFileService" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="FileWebEndPoint">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="FileWorker.ServiceBehaviour">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

Now build and run the application to upload file in the corresponding location.