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是一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件.它主要用于客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机 ...
随机推荐
- linux 内核调试之关键函数名记要
gdbserver + gdb 调试内核 记到函数名,其它就能用gdb看了 start_kernel 内核启动 run_init_process init进程启动 主要是根据shell脚本初始化 ...
- ThinkJava-标准IO
1 从标准输入中读取 按照标准1/0模型, Java提供了System.in.System.out和System.err.在整本书里,我们已经 看到了怎样用System.out将数据写出到标准输出,其 ...
- Java之MD5加密
一.Message Digest Algorithm MD5(中文名为消息摘要算法第五版)为计算机安全领域广泛使用的一种散列函数,用以提供消息的完整性保护.该算法的文件号为RFC 1321(R.Riv ...
- 使用Java配置SpringMVC
在此之前,一直使用的是XML的方式配置SpringMVC,现在为了适应Servlert3.0以及JavaConfig的Spring配置方式,在这里记录一下使用Java代码配置SpringMVC.首先, ...
- Vue 获取数据、事件对象、todolist
vue中在方法里获取data里的msg:this.msg 在微信小程序里this.data.msg 改变data里的msg:this.msg="改变后的msg" 可以通过list. ...
- Oracle表空间知识
Oracle表空间知识 一,创建临时表空间 CREATE temporary TABLESPACE TEMP_PNLREPORT tempfile '/oradata2/ORCL/temp_pnlre ...
- android studio 3.0.1使用笔记(一)20171231
首先安装JDK1.8.1并设置环境变量JAVA_HOME(C:/JAVA/JDK)及PATH(;%JAVA_HOME%\bin ) 然后安装AS 然后首次AS运行并退出,将GRADLE-4-1.ZIP ...
- 《OpenCL异构并行编程实战》补充笔记散点,第一至四章
▶ 总体印象:适合 OpenCL 入门的书,有丰富的代码和说明,例子较为简单.先把 OpenCL 代码的基本结构(平台 → 设备 → 上下文 → 命令队列 → 创建缓冲区 → 读写缓冲区 → 编译代码 ...
- eval函数的使用之一
把从后台传到前端的json格式的字符串转成json success: function(data){ var json =eval("("+data+")"); ...
- 【bzoj1087】互不侵犯King 状态压缩dp
AC通道:http://www.lydsy.com/JudgeOnline/problem.php?id=1087 [题解] 用f[i][j][k]表示前i行放了j个棋子且第i行的状态为k的方案数. ...