使用jquery将文件发布到WCF休息服务

时间:2013-11-23 10:47:12

标签: c# jquery .net wcf web-services

我的帖子方法

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "Service/UpLoadCarPhoto",
    BodyStyle = WebMessageBodyStyle.WrappedRequest,

        ResponseFormat=WebMessageFormat.Json)]
    public string UpLoadCarPhoto(Image imageFile)
    {
        try
        {
            imageFile.Save("c:\\button.gif", System.Drawing.Imaging.ImageFormat.Png);
            return "File Saved";
        }
        catch (Exception e)
        {
            return e.InnerException.InnerException.Message;
        }
     }

我如何调用此方法

@{
    ViewBag.Title = "Home Page";
}
<script src="@Url.Content("~/Scripts/jquery-1.10.2.js")" type="text/javascript"></script>

<div id="divMyLetterImage"></div>
<input type="file" name="UploadImage" id="CarImage"/>
<input type="button" id="uploadImage"/>


<script type="text/javascript">

    var getCarUrl = 'http://localhost:62051/Service/GetCarList';
    var postCarUrl = 'http://localhost:62051/Service/UpLoadCarPhoto';

    $('#uploadImage').click(
    function () {
        var im = $('#CarImage').get(0).files[0];
        alert(im);
        $.ajax({
            cache: false,
            type: "POST",
            url: postCarUrl,
            data: JSON.stringify(im),
            contentType: "application/json; charset=utf-8",
            processData: true,
            success: function (response) {
                alert(response);
            },
            error: function (xhr) {
                alert(xhr.status);
            }
        });

    }
    );

</script>

我的网站配置

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

  <system.web>
      <compilation debug="true" targetFramework="4.0">
        <assemblies>
          <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
        </assemblies>
      </compilation>
  </system.web>

  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" />
      </webHttpEndpoint>
    </standardEndpoints>
  </system.serviceModel>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  <connectionStrings>

    <add name="CarHaatDbContext" connectionString="metadata=res://*/Entities.CarHaatModel.csdl|res://*/Entities.CarHaatModel.ssdl|res://*/Entities.CarHaatModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\CarHaatDatabase.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=False&quot;" providerName="System.Data.EntityClient" />
    <!--<add name="CarHaatDbContext" connectionString="Data Source=.\SQLEXPRESS; 
AttachDbFilename=F:\8-Semester Project\11-20-13\CarHaat\CarHaatWcfService\App_Data\CarHaatDatabase.mdf;
Integrated Security=True; Connect Timeout=30; User Instance=True" />-->
  </connectionStrings>
</configuration>

我收到错误400 Bad Request。我怎样才能上传图片?帮助

1 个答案:

答案 0 :(得分:1)

您的服务配置文件的system.serviceModel部分看起来不完整。 我们至少使用配置文件中的“behavior”和“services”部分来定义REST WCF服务。

<behaviors>
  <endpointBehaviors>
    <behavior name="RestBehavior">
      <webHttp helpEnabled="true" />
    </behavior>   
<behaviors>

 <services>
      <service name="RestService">
        <endpoint behaviorConfiguration="RestBehavior" binding="webHttpBinding"
          name="RestServiceEndpoint" contract="…your contract here …" />
        <host>
          <baseAddresses>
            <add baseAddress="https://localhost:18100/" />
          </baseAddresses>
        </host>
      </service>
    </services>  

以下链接提供了全面的详细信息 http://www.codeproject.com/Articles/571813/A-Beginners-Tutorial-on-Creating-WCF-REST-Services

此致