【问题标题】:Download file using WCF Rest service?使用 WCF Rest 服务下载文件?
【发布时间】:2012-03-15 05:30:07
【问题描述】:

如果有办法Upload file using rest via stream 是否也有“Download”?如果是,你能告诉我怎么做吗?提前致谢!

【问题讨论】:

    标签: c# wcf rest


    【解决方案1】:

    我用来从我的 REST 服务下载文件的示例方法:

    [WebGet(UriTemplate = "file/{id}")]
            public Stream GetPdfFile(string id)
            {
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/txt";
                FileStream f = new FileStream("C:\\Test.txt", FileMode.Open);
                int length = (int)f.Length;
                WebOperationContext.Current.OutgoingResponse.ContentLength = length;
                byte[] buffer = new byte[length];
                int sum = 0;
                int count;
                while((count = f.Read(buffer, sum , length - sum)) > 0 )
                {
                    sum += count;
                }
                f.Close();
                return new MemoryStream(buffer); 
            }
    

    【讨论】:

    • 有什么理由不直接返回 FileStream 吗?如果你真的想复制流,.Net4 在流上有一个 CopyTo 方法。
    • 可能不再相关,但直接返回 FileStream 可能会导致未关闭文件出现问题。
    • 关于 CopyTo - 不要忘记在将文件复制到 MemoryStream 后将流的位置重置为 0。否则,您将在调用方有空文件。
    【解决方案2】:

    你也可以使用下面的

     public Stream GetFile(string id)
     {
          WebOperationContext.Current.OutgoingResponse.ContentType = "application/txt";
          var byt = File.ReadAllBytes("C:\\Test.txt");
          WebOperationContext.Current.OutgoingResponse.ContentLength = byt.Length;
          return new MemoryStream(byt);
     }
    

    当它被定义为时

    [WebGet(UriTemplate = "file/{id}")]
    [OperationContract]
    Stream GetFile(string id);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 2013-06-17
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      相关资源
      最近更新 更多