Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending image in base64 to Webservice - 'application/octet-stream' was not the expected type 'text/xml; charset=utf-8'

I'm trying to save an html5 canvas content, to localhost by using a webserver. I'm getting the canvas value in base64 and I send it to my webservice. But when I send the data to the webservice I get this error and the file is not saved:

415: "Cannot process the message because the content type 'application/octet-stream' was not the expected type 'text/xml; charset=utf-8'."

What am I doing wrong?

Service.vb

Imports System.IO
Imports System.Drawing

Public Class Service
    Implements IService

    Public Sub New()
    End Sub


    Public Function savePictureBase64(bytes As Byte()) As Boolean Implements IService.savePictureBase64
        Dim fullOutputPath As String = "c:\temp\file.png"

        'get a temp image from bytes, instead of loading from disk
        'data:image/gif;base64,


        Dim imagem As Image
        Using ms As New MemoryStream(bytes)
            imagem = Image.FromStream(ms)
        End Using

        File.WriteAllBytes(fullOutputPath, (bytes))

        Return True


    End Function

End Class

IService.vb

<ServiceContract()>
Public Interface IService


    <OperationContract()>
    Function savePictureBase64(bytes As Byte()) As Boolean



    ' TODO: Add your service operations here

End Interface

Javascript

function save () {
              var image = document.getElementById("sketchpad").toDataURL("image/png");
              image = image.replace('data:image/png;base64,', '');
              $.ajax({
            type: 'POST',
            url: 'http://localhost:52193/service.svc',
            data:  image,
            contentType: 'application/octet-stream',
                 success: function (msg) {
                      alert('Image saved successfully !');
                 },
                 error: function(result) {
                    alert("Error");
                }
            });
         }

</script>

web.config

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
  </appSettings>
  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
    <pages>
      <namespaces>
        <add namespace="System.Runtime.Serialization"/>
        <add namespace="System.ServiceModel"/>
        <add namespace="System.ServiceModel.Web"/>
      </namespaces>
    </pages>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="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="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <basicHttpBinding>
        <binding messageEncoding="Mtom">
        </binding>
      </basicHttpBinding>
    </bindings>    
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https"/>
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" 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>
like image 952
RSilva Avatar asked Jan 08 '16 15:01

RSilva


1 Answers

The error is the call that you made by Javascript code. You try to send a string, the webservice expected an XML message:

expected type 'text/xml; charset=utf-8'.

I don't know how complicated it is to compose a webservice XML message from Javascript, but I think that you can change your approach. Your service is hosted under IIS, can you build an HttpHandler?

public class UploadBase64 : IHttpHandler
{
    public bool IsReusable
    {
        get { return true; }
    }
    public void ProcessRequest(HttpContext context)
    {
        string image_string = string.Empty;
        using (StreamReader sr = new StreamReader(context.Request.InputStream))
            image_string = sr.ReadToEnd();
        byte[] image_bin = Convert.FromBase64String(image_string);
        File.WriteAllBytes(@"c:\temp_10\test01.png", image_bin);
    }
}

...and add this to your web.config file:

<system.web>
  <httpHandlers>
    <add verb="POST" path="UploadBase64.aspx" type="WebApplication1.UploadBase64"/>
  </httpHandlers>
</system.web>
like image 157
bdn02 Avatar answered Sep 28 '22 20:09

bdn02