使用WCF RESTFul服务完整的工作示例上传图像 [英] Uploading an image using WCF RESTFul service full working example

查看:167
本文介绍了使用WCF RESTFul服务完整的工作示例上传图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个非常大的应用程序的一部分,我需要提供一个上传图像的REST服务。
由于整个应用程序是.NET,我一直在试图找到一个WCF RESTFul服务的工作示例,但不能(定义整个配置)。网上有一些例子,但是我不能(因为我在WCF中缺乏知识)使它们都不能工作。
(我不断收到异常)



我很乐意把它链接到一个工作。

在服务器上:

接口:

$ p $ [WebInvoke]
字符串PostImage(Stream stream);

我的实现类:

  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();
返回收到服务器上的映像;





注意:确保您的WCF服务应用程序应用程序池标识具有写访问权c:\ Temp位置来写入文件。或者,您可以替换逻辑,以保存图像数据库或任何其他方式你想要它。



我的服务器上的web.config:

 < services> 
< service name =XMLService.Service1behaviorConfiguration =default>
< endpoint address =behaviorConfiguration =webbinding =webHttpBindingbindingConfiguration =RestBindingname =Service1contract =XMLService.IService1/>
< / service>
< / services>
<行为>
< endpointBehaviors>
< behavior name =web>
< webHttp />
< /行为>
< serviceBehaviors>
< behavior name =default>
< dataContractSerializer maxItemsInObjectGraph =2147483647/>
< serviceMetadata httpGetEnabled =true/>
< serviceDebug includeExceptionDetailInFaults =true/>
< /行为>
< / serviceBehaviors>
< /行为>
< webHttpBinding>
< binding name =RestBinding>
< readerQuotas maxStringContentLength =5242880maxArrayLength =16384maxBytesPerRead =4096/>
< security mode =None>
< / security>
< / binding>
< / webHttpBinding>

现在我的客户端上有以下代码:

  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);
字符串responseString;
if(response.StatusCode == HttpStatusCode.OK)
{
responseString = HttpUtility.HtmlDecode(response.Content);
}
else
{
responseString = response.StatusDescription +--------------------+ HttpUtility。 HtmlDecode(response.Content);

我使用第三方工具RestSharp 将我的请求发送到REST服务。

我在fiddler中的请求如下所示:

  POST http://localhost/XMLService/Service1.svc/PostImage HTTP / 1.1 
接受: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 ,放气
连接:保持活动

------------------------------- 28947758029299
内容处理:表单数据; NAME = 流;文件名=download.jpg
内容类型:application / octet-stream

JIFIF C
!'** %% + 7,$ 3)1 - ,* 4696A),,5 C


6 $$ 555 ,,)404,)6,51, 5),)+)),, 0,0.044),1),)),)))42 ,,, 0 !1\" AQ2a#qBRr 1→4ՇOF¼(%azROw升ZG}JqWRʜRK);<&安培; GkwK):1 `\B; E(:U ._ QSiB)2瓦特Qk的{ % e xU ^ !Bw〜 b ) -, e =k s v } $ } 2} O>5NҞYхLT)= | gu B^ͽͽ& :st J 8ae / O-% I
ES } $ MI7',nK8̟xG m F ʤ K g) n^ = #ǎ1 {P $ b $b U5)8 儞8k N f 8 ʧuSM9IK8MxYjEZӖ[YO ۓ(吨ޥHWK2 - M cnM_&安培;公斤夳升;}%AiffQMB {1xofsu sX qsW T )V ʦ' $ $ b b b b n n n n n n n n nn - ,6UsNڞj_r5OӜ8%V NAS> _< JV:的pBݸOA&安培;㕞q> L}的Na {տXUӢ C〜XϜe] 3NrWZM(FKD%'{} 04U M]厥IA%?+ KN ] i n Mgң, S 〜 W ޶ b b b b b b b b b b b b b b b b bb ҩm,.Rry ^ o} Oy公司^ 9NMTG29G +大于7 = ^^ J4 1 %% *YMK Z s 5) Y U y:pj9:*S mU% y 24 I)- qĖ$ C] J4(⛬dgfv; R԰YO + ([Z VЎT R Jks K 8Ͽ$ b $b 4 Wv6 m 6 K y^y $ b $b E 'E Pꗯu ģ
M5 8b 5{ ҧV IB2\6 o̤ O < ;ԚGVRg7,<< |&QTCRxӏGT; 1Vuj< 7 RO)乙֜SYħzP8W$ N 382 4中号U<?; ] /:J + N我ܟ?'Fcytҕ%和4 k90i [FP9֡7中,h S_D%VXSuj턽1sQyϟuyŕi)Е*IŶW Y
& K H K q
zRV 8 #:p krk> > - =' Ժ{ U} e

--------------- ---------------- 28947758029299--



  HTTP / 1.1 200 OK 
Cache-Control :private
Content-Length:105
Content-Type:application / xml; charset = utf-8
服务器:Microsoft-IIS / 7.5
Set-Cookie:ASP.NET_SessionId = fdbg45tergdsfg434t;路径= /; HttpOnly
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
日期:2012年2月27日星期一12:05:32 GMT

< string xmlns =http://schemas.microsoft.com/2003/10/Serialization/>收到服务器上的图片< / string>


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.

解决方案

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>

这篇关于使用WCF RESTFul服务完整的工作示例上传图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆