使用WCF Rest服务下载文件?

时间:2012-03-15 05:30:07

标签: c# wcf rest

如果有Upload file using rest via stream的方式可以使用“Download”吗?如果有,你能告诉我怎么样?提前谢谢!

2 个答案:

答案 0 :(得分:8)

我用来从我的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); 
        }

答案 1 :(得分:0)

您还可以使用以下内容

 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 GetPdfFile(string id);