简体   繁体   中英

Upload a file from Android to WCF in Azure

I'm trying to upload a file from android to azure and its driving me crazy. I think its something in the settings as I've confirmed the code working in IIS with android. Right now I'm able to access the method in c# but my stream is empty at the server. In android I'm getting a 415 error "type mismatch". Any help is HUGELY appreciated!

Here's my c# test client:

            ServiceReference1.PostImage2Request r = new ServiceReference1.PostImage2Request();
            MemoryStream memStream = new MemoryStream();                 
            using (FileStream fileStream = File.OpenRead("C:\\crap.png"))
            {
                memStream.SetLength(fileStream.Length);
                fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
            }
            r.image = memStream;
            ServiceReference1.RestServiceImplClient c = new ServiceReference1.RestServiceImplClient();
            ServiceReference1.PostImage2Response p = c.PostImage2(r);

Here's my client config:

 <system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="BasicHttpBinding_IRestServiceImpl" />
  </basicHttpBinding>
</bindings>
<client>
  <endpoint address="http://testapp.cloudapp.net/Service1.svc"
    binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IRestServiceImpl"
    contract="ServiceReference1.IRestServiceImpl" name="BasicHttpBinding_IRestServiceImpl" />
</client>

Here's my android code:

    String url = "https://testapp.cloudapp.net/Service1.svc/postimage2"; 

        String filepath = String.format(Environment.getExternalStorageDirectory() + "/ImageStorage/1.jpg");

        File f = new File(filepath);

        if (f.exists())
        {
            DefaultHttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(url);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            //This is the new shit to deal with MIME
            MultipartEntity entity = new MultipartEntity();
            entity.addPart("image", new FileBody(f, "multipart/form-data"));

            httppost.setEntity(entity);

            try {
                String responseString = httpclient.execute(httppost, responseHandler);

Here's my server code:

    [OperationContract]
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "PostImage2")]
    string PostImage2(Stream image);

     public string PostImage2(Stream image)
    {
        MultipartParser parser = new MultipartParser(image);

        string content = "testing123";
        try
        {

            if (image == null)
                return "Image stream is null";

            // Read the stream into a byte array
            byte[] data = parser.ToByteArray(image);

            // Copy to a string for header parsing
            content = Encoding.UTF8.GetString(data);

            if (content == "")
                content = "There is no content";

            return content + " - dataLength: " + data.Length.ToString();
        }
        catch (Exception ex)
        {
            return "ERROR" + ex.Message + ex.InnerException + ex.StackTrace;
        }


    }

and here's my server config:

<system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior name="WCFServiceWebRole2.Service1Behavior">
      <!-- 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>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

<bindings>
  <basicHttpBinding>
    <binding name="BasicHttpBinding_WCFServiceWebRole2" transferMode="Streamed" maxBufferSize="10485760" maxReceivedMessageSize="67108864">
      <readerQuotas maxDepth="64" maxStringContentLength="214748364" maxArrayLength="214748364"
          maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <security mode="None">
        <transport clientCredentialType="None" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
<services>
  <service name="WCFServiceWebRole2.Service1" behaviorConfiguration="WCFServiceWebRole2.Service1Behavior">        
    <endpoint address="" binding="basicHttpBinding" contract="WCFServiceWebRole2.IRestServiceImpl"/>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
  </service>
</services>

Is there some particular reason you're using multipart formatting? Typically that's done because you want to send multiple things in one request. For instance, a file and some associated data, or several files, etc. You don't seem to be doing that, so the multipart formatting is just confusing the issue. Unless you have a good reason for the multipart formatting, I'd just drop it altogether. Have your clients send the raw bytes, and have the server code just read directly from the stream, without using MultipartParser .

Also, I notice that once you do get the image data you're going to try to read it as UTF8 data. I'm reasonably certain that won't work, and is probably not the

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM