Search code examples
wcffile-uploadwcf-restimage-uploading

Uploading an image using WCF RESTFul service full working example


As part of a pretty large application I need to provide a REST Service that uploads an image. Since the whole application is .NET, I've been trying to find an working example of a WCF RESTFul Service that does that but couldn't (Which defines the whole configurations). There are handful of examples online but I couldn't (thanks to my lack of knowledge in WCF) make none of them work. (I keep getting exceptions thrown).

I'll be happy to get linked to a working one.


Solution

  • Please find a sample below:

    On Server:

    Interface:

    [WebInvoke]
    string PostImage(Stream stream);
    

    My Implementation class:

    public string PostImage(Stream stream)
            {
                byte[] buffer = new byte[10000];
                stream.Read(buffer, 0, 10000);
                FileStream f = new FileStream("C:\\temp\\sample.jpg", FileMode.OpenOrCreate);
                f.Write(buffer, 0, buffer.Length);
                f.Close();
                stream.Close();
                return "Recieved the image on server";
            }
    

    NOTE: Make sure that your WCF Service application app pools identity has write access to the c:\Temp location to write the file. Alternatively you can replace the logic to save the image to db or any other way you want it to.

    My web.config on server:

    <services>
          <service name="XMLService.Service1" behaviorConfiguration="default">
            <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" bindingConfiguration="RestBinding" name="Service1" contract="XMLService.IService1" />
          </service>
    </services>
    <behaviors>
          <endpointBehaviors>
            <behavior name="web">
              <webHttp />
            </behavior>
      <serviceBehaviors>        
        <behavior name="default">
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <webHttpBinding>
    <binding name="RestBinding">
         <readerQuotas maxStringContentLength="5242880" maxArrayLength="16384" maxBytesPerRead="4096" />
         <security mode="None">            
         </security>
         </binding>
    </webHttpBinding>
    

    Now on my client i have the following code:

    var client = new RestClient();
    client.BaseUrl = "http://localhost/XMLService/Service1.svc";
    var request = new RestRequest(method) { DateFormat = DataFormat.Xml.ToString(), Resource = resourceUrl };
    if(requestBody !=null)
          request.AddParameter("objCompositeType", requestBody);
    request.AddFile("stream", image, "Array.png");    
    var response = client.Execute(request);
    string responseString;
    if (response.StatusCode == HttpStatusCode.OK)
    {
         responseString = HttpUtility.HtmlDecode(response.Content);
    }
    else
    {
         responseString = response.StatusDescription + " --------------------" + HttpUtility.HtmlDecode(response.Content);
    }
    

    I am using a 3rd party tool RestSharp to post my request to the REST Service.

    My request in fiddler looks as shown:

    POST http://localhost/XMLService/Service1.svc/PostImage HTTP/1.1
    Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
    User-Agent: RestSharp 102.0.0.0
    Host: rajeshwin7
    Content-Type: multipart/form-data; boundary=-----------------------------28947758029299
    Content-Length: 2300
    Accept-Encoding: gzip, deflate
    Connection: Keep-Alive
    
    -------------------------------28947758029299
    Content-Disposition: form-data; name="stream"; filename="download.jpg"
    Content-Type: application/octet-stream
    
    �����JFIF����������C�       
    !#'**%%+7,$3)1-,*4696A),,5���C  
    
    
    6$$555,,)404,)6,51,5),)+)),,0,.044,),1),)),)))42,,,0,���"��"������������������.�������!1"AQ2a�#q�B�Rr���������������������������������1�����?��4��������������������ՇOF��¼�(�%�az�ROw����l"���Z��g}J�qWR��ʜR�K)�;���<&���G��kw���K���):1���������`�\�B;e(�:u"����.���_��QS�iB)�2�w�{��Q���k�%�e�xU�^�!Bw~��b�)����-,���e��=k���s��v���}�    ���$�}2}���o�>5N��Ҟ����YхL���T��)=��|�gu�B^ѕͽ&�:st���J�8ae�/�O-%��I���
    ES��}�$��MI7',nK8̟xG���m��F��ʤ�K�g)�n^=�#ǎ1�����{P��
    ��U5)8��儞��8k��N�f����8�ʧu�S�M9��I�K8M�xY���������������j�EZӖ�[Y�O�ۓ(t�ޥH�W�K2�~�M�cn�����M_�����&�K��g������夳�l;��}%A�if�f��Q�MB{1�xofs�u�sX�qsW���T��)V���ʦ'��<���饎S���Y�t
    �=�i�R�:nJsm�U̜T���-���,�6U��s��Nڞ���j�_�r�5OӜ��8�%������������������V���N��as���>_<J��v�:p�BݸO��A�&㕞q���>L}N���a{����տX�U�Ӣ�C���~�XϜe�]���3NrWZ���M(F�kd%'��{0���4�����U}M]J����ue���ia%��?���+K��n]��i���n����Mgң,����S��~�W�޶V�)m�95ы�Rm��q��ı��P�
    m5_wjQ�ҩ��m,.��Rry^��o��}�O�y^9�N��MT�G��2�9G���+>7=^�^��J4��1�%%���*YMK�Z�s�5 )��Y�U�y:pj۹:*S�mU%�y���24��I)-�qĖ$�����C]�J�4�(�����⛬��d����g�fv�;R�԰��yO�+������������������([Z�VЎT�R�Jks�K���8Ͽ
    �4�Wv6�m�6��K�y^y
    ��u������E��������'E�Pꗯu���ģ�
    M5������8b�5{�ҧV�IB2\6��o̤���O���<�Ԛ�GVR��g�7��,<���<��|���Q��T���CRx�ӏ�>1��V���uj<�7'�r�O������������������)B֜�S�Y�ħ�����z�P�8W�$��n~�S�M�?u�<��������������������]����/�:j+n"���I��ܟ�?��,���'F�c�ytҕ%&�4��k9��0�����������������������i�[FP���9֡����7����,���h�S��_d����������������������%V�XSuj턽1sQ����yϟu��yŕ�i�)Е*�IŶ�W��Y�
    &���K�H  ��������������������K�q
    zRV�8�#:p���krk>�>�-�='�Ժ{��U}�e�
    �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
    -------------------------------28947758029299--
    

    And when i perform a POST of the above request i get the below response:

    HTTP/1.1 200 OK
    Cache-Control: private
    Content-Length: 105
    Content-Type: application/xml; charset=utf-8
    Server: Microsoft-IIS/7.5
    Set-Cookie: ASP.NET_SessionId=fdbg45tergdsfg434t; path=/; HttpOnly
    X-AspNet-Version: 4.0.30319
    X-Powered-By: ASP.NET
    Date: Mon, 27 Feb 2012 12:05:32 GMT
    
    <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Recieved the image on server</string>