使用wcf从服务器获取文件并在客户端浏览器下载

Get a file from server using wcf and download at clients browser

本文关键字:客户端 浏览器 下载 文件 wcf 服务器 获取 使用      更新时间:2023-09-26

我有一个WCF服务来读取文件内容,我使用JavaScript在我的网页上调用它,并获得内容作为响应。

现在我要做的是,而不是阅读它的内容,我必须下载这个文件从服务器到客户端系统,任何想法如何做得到一个文件从服务器使用wcf ?

WCF:-

public Stream getFileFromPath(string filepath)
{
String[] filename=filepath.Split('''');            
        WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
        if(File.Exists(filepath)
        {
            String headerInfo = "attachment; filename=" + filename[filename.Length - 1];
            WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = headerInfo;
            return File.OpenRead(filepath);
        }
        else
        {
            String headerInfo = "attachment; filename=" + "error.txt";
            WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = headerInfo;
            string errortext="file not found";
            byte[] byteArray = Encoding.ASCII.GetBytes(errortext);
            MemoryStream stream = new MemoryStream(byteArray);
            return stream;
        }
    }

web . config: -

 <system.serviceModel>
<bindings>
  <webHttpBinding>
    <binding name="MyWcfRestService.WebHttp" maxBufferSize="2147483647"
             maxBufferPoolSize="2147483647"
             maxReceivedMessageSize="2147483647"
             transferMode="Streamed"
             sendTimeout="00:05:00">
      <readerQuotas  maxDepth="2147483647"
                     maxStringContentLength="2147483647"
                     maxArrayLength="2147483647"
                     maxBytesPerRead="2147483647"
                     maxNameTableCharCount="2147483647"/>
      <security mode="None" />
    </binding>
  </webHttpBinding>
</bindings>
<services>
   <service behaviorConfiguration="MyWcfRestService.FileUploadServBehavior" name="MyWcfRestService.FileUploadServ">
    <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" bindingConfiguration="MyWcfRestService.WebHttp" contract="MyWcfRestService.IFileUploadServ">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
  </service>
</services>
<behaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp  helpEnabled=”true”/>
    </behavior>
  </endpointBehaviors>
  <serviceBehaviors>
    <behavior name="MyWcfRestService.FileUploadServBehavior">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>
</behaviors>

JavaScript

: -

 function downloadfile(filepath)
 {    
 var url="https://abc/service.svc/getfilestream?v="+filepath;
 window.open(url,"windowname","width:400,height:300");
 }