转载

Restful风格wcf调用3——Stream

写在前面

上篇文章介绍了restful接口的增删改查,本篇文章将介绍,如何通过数据流进行文件的上传及下载操作。

系列文章

Restful风格wcf调用

Restful风格wcf调用2——增删改查

一个例子

添加一个wcf服务,并在global.asax中注册路由,并修改svc文件的标记,添加Factory属性。

//注册路由             System.Web.Routing.RouteTable.Routes.Add(new System.ServiceModel.Activation.ServiceRoute(                 "imageService", new System.ServiceModel.Activation.WebServiceHostFactory(), typeof(ImageService)));
<%@ ServiceHost Language="C#" Debug="true" Service="Wolfy.WCFRestfuleDemo.ImageService" CodeBehind="ImageService.svc.cs"  Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

契约

namespace Wolfy.WCFRestfuleDemo {     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IImageService" in both code and config file together.     [ServiceContract]     public interface IImageService     {  /// <summary>  /// 根据图片的相对路径获取文件流  /// </summary>  /// <param name="imgUrl"></param>  /// <returns></returns>  [OperationContract]  [WebGet(UriTemplate = "api/{imagUrl}")]  Stream GetImageStream(string imgUrl);  /// <summary>  /// 上传图片  /// </summary>  /// <param name="imgStream"></param>  /// <param name="imageName"></param>  [OperationContract]  [WebInvoke(UriTemplate = "api/{imageName}", Method = "POST")]  void UploadImage(Stream imgStream, string imageName);  /// <summary>  /// 获得所有图片的相对路径  /// </summary>  /// <returns></returns>  [OperationContract]  [WebGet(UriTemplate = "api/list", ResponseFormat = WebMessageFormat.Xml)]  string[] GetImages();     } } 

实现

using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; namespace Wolfy.WCFRestfuleDemo {  // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ImageService" in code, svc and config file together.  // NOTE: In order to launch WCF Test Client for testing this service, please select ImageService.svc or ImageService.svc.cs at the Solution Explorer and start debugging.  public class ImageService : IImageService  {   /// <summary>   /// 根据图片的相对路径获取文件流   /// </summary>   /// <param name="imgUrl"></param>   /// <returns></returns>   public System.IO.Stream GetImageStream(string imgUrl)   {    var contentType = Path.GetExtension(imgUrl).Trim('.');    WebOperationContext woc = WebOperationContext.Current;    //根据请求的图片类型,动态设置contenttype    woc.OutgoingResponse.ContentType = "image/" + contentType;    string savePath = System.Web.HttpContext.Current.Server.MapPath("/Images");    string filePath = Path.Combine(savePath, imgUrl);    return File.OpenRead(filePath);   }   /// <summary>   /// 上传图片   /// </summary>   /// <param name="imgStream"></param>   /// <param name="imageName"></param>   public void UploadImage(System.IO.Stream imgStream, string imageName)   {    var dir = System.Web.HttpContext.Current.Server.MapPath("~/Images");    var file = Path.Combine(dir, imageName);    var bitmap = Bitmap.FromStream(imgStream);    bitmap.Save(file);   }   /// <summary>   /// 获得所有图片的相对路径   /// </summary>   /// <returns></returns>   public string[] GetImages()   {    List<string> lstImages = new List<string>();    var dir = System.Web.HttpContext.Current.Server.MapPath("~/Images");    string[] paths = Directory.GetFiles(dir);    for (int i = 0; i < paths.Length; i++)    {     lstImages.Add(paths[i].Replace(dir, ""));    }    return lstImages.ToArray();   }  } } 

首先,进行上传文件1.jpg

try {  var httpClient = new HttpClient();  var strPostUrl = "http://localhost:21074/imageService/api/{0}";  string fileName = Path.GetFileName("1.jpg");  FileStream fs = new FileStream("1.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);  HttpResponseMessage response = httpClient.Post(string.Format(strPostUrl, fileName), HttpContent.Create(fs));  fs.Dispose();  Console.WriteLine("上传成功"); } catch (Exception) {  throw; } 

客户端提示

Restful风格wcf调用3——Stream

查看Images目录,1.jpg已经上传成功。

通过restful服务在浏览器中查看:在浏览器中发送get请求,将会调用GetImageStream方法,将stream响应给浏览器,浏览器进行渲染。

Restful风格wcf调用3——Stream

还剩最后一个接口测试,返回所有的图片。因为wcf寄宿的也是一个web站点,所以也可以通过在浏览器中直接调用,将会返回所有的图片的相对路径的xml信息并在页面上进行展示。

Restful风格wcf调用3——Stream

总结

本文介绍了restful接口如何处理post过来的stream,以及如何返回stream给客户端的方式,这里也是一种上传下载文件的一种方式。

参考资料

http://blog.csdn.net/fangxing80/article/details/6261431

正文到此结束
Loading...