Uploading an image using WCF RESTFul service full

2020-01-29 06:16发布

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.

2条回答
一夜七次
2楼-- · 2020-01-29 06:56

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>
查看更多
趁早两清
3楼-- · 2020-01-29 07:06

Here is what I have done:

Create C# Windows console application

class Program
{

    static void Main(string[] args)
    {
        Console.WriteLine("hello World");

        System.Uri url = new System.Uri("http://192.168.1.12:81/WebService/BIITAlumni.svc/UploadImage");
        string filePath = @"F:\temp\Desert.jpg";



            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Accept = "application/octet-stream";
            request.Method = "POST";
            request.ContentType = "image/jpeg";
            using (Stream fileStream = File.OpenRead(filePath))
            using (Stream requestStream = request.GetRequestStream())
            {
                int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                int byteCount = 0;
                while ((byteCount = fileStream.Read(buffer, 0, bufferSize)) > 0)
                {
                    requestStream.Write(buffer, 0, byteCount);
                }
            }
            string result;
            using (WebResponse response = request.GetResponse())
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
            result = reader.ReadToEnd();
            }
            Console.WriteLine(result);
    }
  }

Create a new project of WCF Service remove namespace AlumniService from this code and replace your own namespace also interface IBIITAlumni too

 namespace AlumniService{

 [ServiceContract]
 public interface IBIITAlumni
 {

    [OperationContract]
    [WebInvoke(
        Method = "POST",
        UriTemplate = "/UploadImage", 
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json)]

    public string UploadImage(Stream stream)
    {
        byte[] buffer = new byte[10000];
        stream.Read(buffer, 0, 10000);
        FileStream f = new FileStream(@"C:\Users\shahzad\Documents\Visual Studio 2013\Projects\AlumniService\FileUpload\sample.jpg", FileMode.OpenOrCreate);
        f.Write(buffer, 0, buffer.Length);
        f.Close();
        stream.Close();
        return "Recieved the image on server";
    }

   }
 }

Changes in web.config

<system.serviceModel>
<bindings>
  <webHttpBinding>
    <binding name="ServiceWebBindingName" transferMode="Streamed" maxReceivedMessageSize="2147483647" >
      <readerQuotas  maxArrayLength="2147483647" maxStringContentLength="2147483647" />
      <security mode="TransportCredentialOnly">
        <transport clientCredentialType="Windows"></transport>
      </security>
    </binding>
  </webHttpBinding>
</bindings>

   <!-- your other configuration goes  here-->
</system.serviceModel>

Enjoy!

查看更多
登录 后发表回答