简体   繁体   English

如何在WCF服务上接收多部分表单数据。 我已经使用手机差距文件传输插件上传功能上传了它

[英]How to Receive Multipart Form Data on WCF Service. I have uploaded it using the phone gap file transfer plugin upload function

How can I receive multipart form data in a WCF Service? 如何在WCF服务中接收多部分表单数据? I have uploaded it using the phone gap file transfer plugin upload function. 我已经使用手机差距文件传输插件上传功能上传了它。

Below are the two functions that I'm trying to call: 以下是我要调用的两个函数:

    ///<summary>
    ///Method for file upload
    ///</summary>
    [OperationContract]
    [WebInvoke(
        Method = "POST",
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "Upload")]
    string Upload(Stream data);


    [OperationContract]
    [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "UploadImage")]
   string UploadImage();

    // TODO: Add your service operations here

I successfully hit the UploadImage function but I don't know how to read a file from the uploaded data. 我成功点击了UploadImage函数,但是我不知道如何从上传的数据中读取文件。

When I try 当我尝试

HttpPostedFile file = HttpContext.Current.Request.Files["recFile"];

I get the error: 我得到错误:

    HttpContext.Current.Request.Files   'HttpContext.Current.Request.Files' threw an exception of type 'System.Web.HttpException'   System.Web.HttpFileCollection {System.Web.HttpException}
    base    {"This method or property is not supported after HttpRequest.GetBufferlessInputStream has been invoked."}   

This is my web.config file: 这是我的web.config文件:

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
     <customErrors mode="RemoteOnly"/>
    <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="CacheFor10Seconds" duration="10"
               varyByParam="none" />
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
    <httpRuntime maxRequestLength="2000000000"/>
  </system.web>
  <appSettings>

    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
  </appSettings>
  <system.serviceModel>
    <bindings>
      <webHttpBinding>
            <binding name="webHttpBindingWithJsonP"
                 crossDomainScriptAccessEnabled="true" maxBufferSize="2000000000"
                maxReceivedMessageSize="2000000000"
              transferMode="Streamed"   />
      </webHttpBinding>
    </bindings>
    <behaviors>

      <endpointBehaviors>
        <behavior name="webHttpBehavior">
          <webHttp helpEnabled="true"/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"  />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
        multipleSiteBindingsEnabled="true" />
    <services>
      <service name="Service.Service1">

        <endpoint name="mexHttpBinding"
                  address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange"
                  />
        <endpoint address="" behaviorConfiguration="webHttpBehavior"
            binding="webHttpBinding"
                  bindingConfiguration="webHttpBindingWithJsonP"
            contract="Service.IService1" />

      </service>
    </services>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

I got the problem it with the Wcf version targetFramework="4.5" issue , 我遇到了Wcf版本targetFramework =“ 4.5”问题,

you have to add below code in web config than the issue get resolve: 您必须在网络配置中添加以下代码,这样才能解决问题:

<appSettings>

    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
    <add key="wcf:serviceHostingEnvironment:useClassicReadEntityBodyMode" value="true" />
  </appSettings>

my all the other web Config that i post already here is working fine below is the updated web config setting 我已经在此处发布的所有其他Web配置在下面可以正常工作是更新的Web配置设置

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
     <customErrors mode="RemoteOnly"/>
    <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="CacheFor10Seconds" duration="10"
               varyByParam="none" />
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
    <httpRuntime maxRequestLength="2000000000"/>
  </system.web>
<appSettings>

    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
    <add key="wcf:serviceHostingEnvironment:useClassicReadEntityBodyMode" value="true" />
  </appSettings>
  <system.serviceModel>
    <bindings>
      <webHttpBinding>
            <binding name="webHttpBindingWithJsonP"
                 crossDomainScriptAccessEnabled="true" maxBufferSize="2000000000"
                maxReceivedMessageSize="2000000000"
              transferMode="Streamed"   />
      </webHttpBinding>
    </bindings>
    <behaviors>

      <endpointBehaviors>
        <behavior name="webHttpBehavior">
          <webHttp helpEnabled="true"/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"  />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
        multipleSiteBindingsEnabled="true" />
    <services>
      <service name="Service.Service1">

        <endpoint name="mexHttpBinding"
                  address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange"
                  />
        <endpoint address="" behaviorConfiguration="webHttpBehavior"
            binding="webHttpBinding"
                  bindingConfiguration="webHttpBindingWithJsonP"
            contract="Service.IService1" />

      </service>
    </services>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

This is my Service and IService Code: 这是我的服务和IService代码:

[OperationContract]
        [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "UploadImage")]
       string UploadImage();



 #region 
        ///<summary>
        ///Metohd to upload image.
        ///</summary>
       public string UploadImage()
       {
           string JsonString = string.Empty;
           JsonString = AppDomain.CurrentDomain.BaseDirectory;

           try {


               HttpPostedFile file = HttpContext.Current.Request.Files[0];

               ;
               if (file == null)
               {
                   RC.ErrorLog.LogFileWrite("<Exception>File is null</Exception>" + JsonString);
                   return JsonString; 
               }

               string targetFilePath = AppDomain.CurrentDomain.BaseDirectory + @"Images\Upload" + Guid.NewGuid() + file.FileName.ToString();
                file.SaveAs(targetFilePath);
                return file.FileName.ToString();





           }
           catch(Exception e) 
           {

               string errorMessage = RC.ErrorLog.CreateErrorMessage(e);
               RC.ErrorLog.LogFileWrite(errorMessage+JsonString);
               return JsonString;
           }

       }
        #endregion

And below is my JqueryMobile code for PhoneGap 下面是我的PhoneGap的JqueryMobile代码

// A button will call this function
//
function captureImage() {
    // Launch device camera application, 
    // allowing user to capture up to 2 images
    debugger;
    navigator.device.capture.captureImage(captureSuccess, captureError, { limit: 2 });
}


function captureSuccess(mediaFiles) {
    var i, len;
    for (i = 0, len = mediaFiles.length; i < len; i += 1) {
        uploadFile(mediaFiles[i]);
    }
}

// Called if something bad happens.
// 
function captureError(error) {
    var msg = 'An error occurred during capture: ' + error.code;
    navigator.notification.alert(msg, null, 'Uh oh!');
}



function uploadFile(mediaFile) {
    var ft = new FileTransfer();
    path = mediaFile.fullPath;
    name = mediaFile.name;
    debugger;
// below varible contain the Server url name that i created by joining defenrent 3 var of //my application
    var objUrl = _ServicesUrl._SecondServicePath + _ServicePage._BaseServicePage + _WcfFunctionUrl._ImageUpload;
    alert("uploadImage");
    ft.upload(path,
        objUrl,
        function (result) {

            alert('Upload success: ' + result.responseCode);
            alert(result.bytesSent + ' bytes sent');
            debugger;
            var abc = JSON.parse(result.Upload);
            alert(abc);

        },
        function (error) {
            alert('Error uploading file ' + path + ': ' + error.code);
        },
        { fileName: name });
}

Hope the answer will help the community. 希望答案能对社区有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用WCF服务传输大于16kb的上传文件 - How to transfer uploaded file size greater than 16kb using wcf service 如何使用WCF服务和javascript表单发布上传.doc文件 - How to upload a .doc file using WCF service and javascript form post 如何从 WCF 服务返回多部分/表单数据作为响应 - How to return multipart/form-data from WCF Service in response Windows Service中的WCF。 如何使用app.config更改端点地址(PORT)并将更新的数据应用于Windows Service中的WCF? - WCF in Windows Service. How do I change the endpoint address (PORT) using app.config and apply an updated data to wcf in windows service? 如何使用WCF服务在angularjs中上传文件? - How to upload file in angularjs using wcf service? Kendo UI Upload:如何使用WCF服务从多部分表单上传中提取文件内容 - Kendo UI Upload : how to extract file content from a multi-part form upload using WCF service WCF服务。 在哪里添加。 svc文件 - WCF service. Where to add . svc file 使用带有basichttpbinding的WCF服务传输较大的文件 - Transfer larger file using WCF service with basichttpbinding 如何将文件上传到WCF服务? - How to upload a file to a WCF Service? WCF服务接受后期编码的多部分/表单数据 - WCF service to accept a post encoded multipart/form-data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM