将base64中的图像发送到Webservice - 'application/octet-stream'不是预期的类型'text/xml; 字符集= UTF-8'

RSi*_*lva 9 javascript vb.net html5 web-services

我正在尝试使用网络服务器将html5画布内容保存到localhost.我在base64中获得了canvas值,然后将其发送到我的webservice.但是,当我将数据发送到Web服务时,我收到此错误,并且文件未保存:

415:"无法处理消息,因为内容类型'application/octet-stream'不是预期类型'text/xml; charset = utf-8'."

我究竟做错了什么?

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
Run Code Online (Sandbox Code Playgroud)

IService.vb

<ServiceContract()>
Public Interface IService


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



    ' TODO: Add your service operations here

End Interface
Run Code Online (Sandbox Code Playgroud)

使用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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

bdn*_*n02 4

该错误是您通过 Javascript 代码进行的调用。您尝试发送一个字符串,Web 服务需要一条 XML 消息:

预期类型 'text/xml; 字符集=utf-8'。

我不知道从 Javascript 编写 Web 服务 XML 消息有多复杂,但我认为您可以改变您的方法。您的服务托管在 IIS 下,您可以构建 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

...并将其添加到您的web.config文件中:

<system.web>
  <httpHandlers>
    <add verb="POST" path="UploadBase64.aspx" type="WebApplication1.UploadBase64"/>
  </httpHandlers>
</system.web>
Run Code Online (Sandbox Code Playgroud)