发送图像文件从Android的WCF到REST服务 [英] Sending Image Files from Android to WCF REST Service

查看:248
本文介绍了发送图像文件从Android的WCF到REST服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经提到很多的解决方案,但没有运气的。

我想从Android发送图片文件,使用WCF REST服务服务器。但我能够发送图片文件,其他的只有10KB然后,我无法发送。

早期我试着发送Base64编码字符串,但我不能用这个方法来发送。换了好几配置WCF中的配置文件,但仍然有问题,以接收大型文件。

下面是我的Andr​​oid code在那里我有异步执行

Android客户端code。使用WCF REST服务发送图片文件到服务器

 公共无效myGoal()
{       位图位图= BitmapFactory.de codeResource(getResources(),R.drawable.courserequest);
    ByteArrayOutputStream BOS =新ByteArrayOutputStream();
    bitmap.com preSS(比较pressFormat.JPEG,50,BOS);
    字节[]数据= bos.toByteArray();
    StringBuilder的S;
    //使HTTP请求
    尝试{
        // defaultHttpClient
        DefaultHttpClient的HttpClient =新DefaultHttpClient();        最后弦乐URL1 =HTTP://本地主机:8889 /照片服务/ WcfAndroidImageService.svc / GetStream
        HttpPost httpPost =新HttpPost(URL1);        ContentBody斌= NULL;        httpPost.setEntity(新ByteArrayEntity(数据));        HTT presponse响应= httpClient.execute(httpPost);
        读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
                。response.getEntity()的getContent(),UTF-8));
        串sResponse;
         S =新的StringBuilder();        而((sResponse = reader.readLine())!= NULL){
            S = s.append(sResponse);
        }
        的System.out.println(回应:+ S);
    }赶上(例外五){
        Log.e(e.getClass()的getName(),e.​​getMessage());
    }}

Web.config文件中的WCF REST服务来添加配置功能

 <?XML版本=1.0&GT?;
<结构>  <&的System.Web GT;
    <编译调试=真targetFramework =4.0/>
    <的httpRuntime的maxRequestLength =2097151useFullyQualifiedRedirectUrl =真
      executionTimeout =14400/>
  < /system.web>
  < system.serviceModel>
    <服务和GT;
      <服务名称=WcfAndroidPhotoServis.WcfAndroidImageServicebehaviorConfiguration =BehConfig>
        <端点地址=
              绑定=的WebHttpBinding
                 behaviorConfiguration =网
              合同=WcfAndroidPhotoServis.IWcfAndroidImageService/>
        <主机>
          < baseAddresses>
            <添加baseAddress =HTTP://本地主机:8889 /照片服务/ WcfAndroidImageService.svc/>
          < / baseAddresses>
        < /主机>
      < /服务>
    < /服务>
    <&绑定GT;
      <&的WebHttpBinding GT;
        <绑定名称=WebBinding
          bypassProxyOnLocal =真
                 useDefaultWebProxy =假
                 hostNameComparisonMode =WeakWildcard
                 的SendTimeout =十点15分00秒
                 openTimeout =十点15分00秒
                 receiveTimeout =10时15分00秒
                 maxReceivedMessageSize =2147483647                 MAXBUFFERSIZE =2147483647
                 maxBufferPoolSize =2147483647
                        transferMode =流                 >          &所述; readerQuotas MAXDEPTH =128
          maxStringContentLength =2147483647maxArrayLength =2147483647
          maxBytesPerRead =2147483647maxNameTableCharCount =2147483647/>        < /&结合GT;
      < /&的WebHttpBinding GT;
    < /绑定>
    <&行为GT;
      < serviceBehaviors>
        <行为NAME =BehConfig>
          <! - 为了避免泄露的元数据信息,下面设置为false值部署之前 - >
          < serviceMetadata httpGetEnabled =真/>
          <! - 要接收故障中的异常细节进行调试,下面设置为true值。设置为false部署之前,以避免泄露异常信息 - >
          < serviceDebug includeExceptionDetailInFaults =真/>
        < /行为>
      < / serviceBehaviors>
      < endpointBehaviors>
        <行为NAME =网络>
          < webHttp automaticFormatSelectionEnabled =真helpEnabled =真defaultOutgoingResponseFormat =JSON的/>
          < D​​ataContractSerializer的maxItemsInObjectGraph =2147483647/>
        < /行为>
      < / endpointBehaviors>
    < /行为>
    < serviceHostingEnvironment multipleSiteBindingsEnabled =真/>
  < /system.serviceModel>
  < system.webServer>
    <模块runAllManagedModulesForAllRequests =真/>
    <! -
        为了调试过程中浏览Web应用程序根目录,下面设置为true值。
        设置为false部署之前,以避免泄露Web应用程序文件夹的信息。
       - >
    < directoryBrowse启用=真/>
  < /system.webServer>< /结构>

在WCF图像服务接口方法

  IWcfAndroidImageService.cs  [OperationContract的]
        [WebInvoke(方法=POST
                RequestFormat = WebMessageFormat.Json,
                ResponseFormat = WebMessageFormat.Json,
              // BodyStyle = WebMessageBodyStyle.Bare,
                UriTemplate =GetStream)]
        无效GetStream(流为imageData);

图像服务方法接收字节流数据从客户端如Android(WcfAndroidImageService.svc.cs)

 公共无效GetStream(流为imageData)
        {
            尝试
            {
                字节[]缓冲区=新的字节[10000]
                imageData.Read(缓冲液,0,10000);
                的FileStream F =新的FileStream(D:\\\\ \\\\的FileUpload SubjectFront.JPG,FileMode.OpenOrCreate);
                f.Write(缓冲液,0,buffer.Length);
                f.Close();
                imageData.Close();
            }
            赶上(异常前)
            {
            }
        }


解决方案

  imageData.Read(缓冲,0,10000);
 f.Write(缓冲液,0,buffer.Length);

您正在做的只有一次。所以,你只能得到10000字节。其余部分被丢失。

请您在这里继续读,直到流的末尾循环。

 内部NREAD = imageData.Read(缓冲,0,10000);
f.Write(缓冲液,0,NREAD);

I have referred lot of solutions but no luck.

I am trying to send Image file from Android to Server using WCF REST Service. But I am able to send only 10KB of image files, other then that I am unable to send.

Early I tried sending Base64 String but I am unable to send using this method. Changed several configurations in WCF config file but still having issues to receive large files.

Below is my Android Code where I have executed asynchronously

Android Client Code to Send Image Files using WCF REST Service to Server

public void myGoal()
{

       Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.courserequest);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 50, bos);
    byte[] data = bos.toByteArray();
    StringBuilder s;


    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();

        final String URL1 = "http://localhost:8889/PhotoService/WcfAndroidImageService.svc/GetStream";
        HttpPost httpPost = new HttpPost(URL1);

        ContentBody bin = null;

        httpPost.setEntity(new ByteArrayEntity(data));  



        HttpResponse response = httpClient.execute(httpPost);
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent(), "UTF-8"));
        String sResponse;
         s = new StringBuilder();

        while ((sResponse = reader.readLine()) != null) {
            s = s.append(sResponse);
        }
        System.out.println("Response: " + s);
    } catch (Exception e) {
        Log.e(e.getClass().getName(), e.getMessage());
    }

}

Web.Config File in WCF REST Service to add configuration features

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime maxRequestLength="2097151" useFullyQualifiedRedirectUrl="true"
      executionTimeout="14400"   />
  </system.web>
  <system.serviceModel>


    <services>
      <service name="WcfAndroidPhotoServis.WcfAndroidImageService" behaviorConfiguration="BehConfig">
        <endpoint address=""
              binding="webHttpBinding"
                 behaviorConfiguration="web"
              contract="WcfAndroidPhotoServis.IWcfAndroidImageService"/>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8889/PhotoService/WcfAndroidImageService.svc"/>
          </baseAddresses>
        </host>
      </service>
    </services>


    <bindings>
      <webHttpBinding>
        <binding name="WebBinding"
          bypassProxyOnLocal="true"
                 useDefaultWebProxy="false"
                 hostNameComparisonMode="WeakWildcard"
                 sendTimeout="10:15:00"
                 openTimeout="10:15:00"
                 receiveTimeout="10:15:00"
                 maxReceivedMessageSize="2147483647"

                 maxBufferSize="2147483647"
                 maxBufferPoolSize="2147483647"
                        transferMode="Streamed"

                 >

          <readerQuotas maxDepth="128"
          maxStringContentLength="2147483647" maxArrayLength="2147483647"
          maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />

        </binding>
      </webHttpBinding>
    </bindings>




    <behaviors>
      <serviceBehaviors>
        <behavior name="BehConfig" >
          <!-- To avoid disclosing metadata information, set the value below to false before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp automaticFormatSelectionEnabled="true"  helpEnabled="true"  defaultOutgoingResponseFormat="Json" />


          <dataContractSerializer maxItemsInObjectGraph="2147483647"  />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

Image Service Interface Method in WCF

IWcfAndroidImageService.cs

  [OperationContract]
        [WebInvoke(Method = "POST",
                RequestFormat = WebMessageFormat.Json,
                ResponseFormat = WebMessageFormat.Json,
              //BodyStyle = WebMessageBodyStyle.Bare,
                UriTemplate = "GetStream")]
        void GetStream(Stream imageData);

Image Service Method to Receive Byte Stream Data From Clients like Android (WcfAndroidImageService.svc.cs)

   public void GetStream(Stream imageData)
        {
            try
            {
                byte[] buffer = new byte[10000];
                imageData.Read(buffer, 0, 10000);
                FileStream f = new FileStream("D:\\FileUpload\\SubjectFront.JPG", FileMode.OpenOrCreate);
                f.Write(buffer, 0, buffer.Length);
                f.Close();
                imageData.Close();
            }
            catch (Exception ex)
            {
            }
        }

解决方案

 imageData.Read(buffer, 0, 10000);
 f.Write(buffer, 0, buffer.Length);

You are doing that only once. So you only get 10000 bytes. The rest is lost.

Make a loop where you keep reading until the end of stream.

Int nread = imageData.Read(buffer, 0, 10000);
f.Write(buffer, 0, nread);

这篇关于发送图像文件从Android的WCF到REST服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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