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 = ; 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
Restful风格wcf调用3——Stream的更多相关文章
- Restful风格wcf调用4——权限认证
写在前面 在前面的三篇文章,已经介绍了restful风格wcf,如何实现增删改查以及文件的上传下载操作.本篇文章将介绍一下,调用restful的权限认证的内容.在调用的接口,为了安全,总会需要对请求进 ...
- Restful风格wcf调用
文章:Restful风格wcf调用 作者相当于把wcf服务改造成rest风格. Restful风格wcf调用2——增删改查 这篇文章在第一篇的基础上,进行了优化. Restful风格wcf调用3——S ...
- Restful风格wcf调用2——增删改查
写在前面 上篇文章介绍如何将wcf项目,修改成restful风格的接口,并在上面提供了查询的功能,上篇文章中也感谢园友在评论中的提的建议,自己也思考了下,确实是那个道理.在urltemplate中,定 ...
- 构建RESTful风格的WCF服务
构建RESTful风格的WCF服务 RESTful Wcf是一种基于Http协议的服务架构风格. 相较 WCF.WebService 使用 SOAP.WSDL.WS-* 而言,几乎所有的语言和网络平台 ...
- spring boot / cloud (十四) 微服务间远程服务调用的认证和鉴权的思考和设计,以及restFul风格的url匹配拦截方法
spring boot / cloud (十四) 微服务间远程服务调用的认证和鉴权的思考和设计,以及restFul风格的url匹配拦截方法 前言 本篇接着<spring boot / cloud ...
- PHP实现RESTful风格的API实例(二)
接前一篇PHP实现RESTful风格的API实例(一) Response.php :包含一个Request类,即输出类.根据接收到的Content-Type,将Request类返回的数组拼接成对应的格 ...
- PHP实现RESTful风格的API实例(一)
最近看了一些关于RESTful的资料,自己动手也写了一个RESTful实例,以下是源码 目录详情: restful/ Request.php 数据操作类 Response.php 输出类 index. ...
- 用cxf开发restful风格的WebService
我们都知道cxf还可以开发restful风格的webService,下面是利用maven+spring4+cxf搭建webService服务端和客户端Demo 1.pom.xml <projec ...
- Restful风格API接口开发springMVC篇
Restful风格的API是一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件.它主要用于客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机 ...
随机推荐
- 【ZedGraph】右键菜单和鼠标滚轴的移动缩放等功能的启用和禁用 (转)
通过[ZedGraph]控件属性修改: 1.禁用右键菜单: IsShowContextMenu = false; 2.禁用鼠标滚轴移动: IsEnableHPan = false; //禁止横向移动; ...
- C++ 函数特性_参数默认值
函数参数默认值写法 有默认参数值的参数必须在参数表的最右边 ,) // 这是正确的写法 , int k) // 这是错误写法 先声明,后定义 在写函数时要先在代码前面声明,然后再去定义. 函数默认参数 ...
- python使用scikit-learn计算TF-IDF
1 Scikit-learn下载安装 1.1 简介 1.2 安装软件 2 TF-IDF基础知识 2.1 TF-IDF概念 2.2 举例说明计算 3 Scikit-Learn中计算TF-IDF 3.1 ...
- Dynamics CRM 2011 权限管理
CRM系统基于角色的权限主要通过部门.角色.用户.团队来进行控制.每一个实体记录的所有者(Owner)必然是某一个用户或团队.一个用户或团队必然归属于一个且只归属于一个部门,但团队的成员即用户可以来自 ...
- predict.glm -> which class does it predict?
Jul 10, 2009; 10:46pm predict.glm -> which class does it predict? 2 posts Hi, I have a question a ...
- IntelliJ IDEA—IDEA2018.1激活方式
前言 以前用过2015的版本,后面就没有使用了,现在又重新用起来了,突然发现激活好难,通过网上找破解方式,总算找到了一种可以实现破解的方法了.. 破解方式 本人使用的是使用破解补丁的方式实现破解的,此 ...
- git_基本使用
1.默认你已经安装了,git的客户端,这里我们使用git bash操作. 2.执行git init命令: git ini 3.在本地创建ssh key: ssh-keygen -t rsa - ...
- LUA 删除元素的问题
table在删除元素时要注意,例t = { "hello", "world", "!"}t[1] = nil此时print(#t) --输出 ...
- 迷你MVVM框架 avalonjs 1.2.5发布
avalon1.2.5发布,升级ms-widget,整合avalon.require.text到核心,并且修复了avalon.mobile的avalon.innerHTML方法的BUG,让它能执行脚本 ...
- 股票F10
[股票F10] 股票非行情类的基本面资料统称为股票F10 在各种金融行情终端软件中,用户通过键盘上的F10快捷键,可迅速查看上市公司的非行情信息,诸如:公司概况.财务数据.公司公告.公司新闻.经营 ...