Restful风格wcf调用3——Stream
写在前面
上篇文章介绍了restful接口的增删改查,本篇文章将介绍,如何通过数据流进行文件的上传及下载操作。
系列文章
一个例子
添加一个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; }
客户端提示
查看Images目录,1.jpg已经上传成功。
通过restful服务在浏览器中查看:在浏览器中发送get请求,将会调用GetImageStream方法,将stream响应给浏览器,浏览器进行渲染。
还剩最后一个接口测试,返回所有的图片。因为wcf寄宿的也是一个web站点,所以也可以通过在浏览器中直接调用,将会返回所有的图片的相对路径的xml信息并在页面上进行展示。
总结
本文介绍了restful接口如何处理post过来的stream,以及如何返回stream给客户端的方式,这里也是一种上传下载文件的一种方式。
参考资料
http://blog.csdn.net/fangxing80/article/details/6261431
-
博客地址:http://www.cnblogs.com/wolf-sun/
博客版权:如果文中有不妥或者错误的地方还望高手的你指出,以免误人子弟。如果觉得本文对你有所帮助不如【推荐】一下!如果你有更好的建议,不如留言一起讨论,共同进步! 再次感谢您耐心的读完本篇文章。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义