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是一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件.它主要用于客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机 ...
随机推荐
- bzoj 5006(洛谷 4547) [THUWC2017]Bipartite 随机二分图——期望DP
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=5006 https://www.luogu.org/problemnew/show/P4547 ...
- CentOS6.5 下Haproxy服务的安装与配置
参考网站: http://wenku.baidu.com/link?url=57AsCAL8TIv8NC3Vdnpd0hQ4fGNls8RFikjRWna3OaZb6qGHYTdV-4_wQPuzv8 ...
- windows server 2012 双网卡配置
别用route 命令!!!!!! 在使用最新版的windows server 2012的时候,当存在两个或者多个网段的时候,就可以采用双网卡的方式来添加和配置路由.具体的设置方法如下: 网段1 19 ...
- 使用用WCF中的双工(Duplex)模式将广告图片推送到每个Winform客户端机子上
参考资料地址:http://www.cnblogs.com/server126/archive/2011/08/11/2134942.html 代码实现: WCF宿主(服务端) IServices.c ...
- spring的定时任务配置(注解)
参考博客: http://www.jb51.net/article/110541.htm http://blog.csdn.net/wxwzy738/article/details/25158787 ...
- Tensorflow笔记——神经网络图像识别(四)搭建模块化的神经网络八股(正则化,指数衰减学习率,滑动平均等优化)
实战案例: 数据X[x0,x1]为正太分布随机点, 标注Y_,当x0*x0+x1*x1<2时,y_=1(红),否则y_=0(蓝) 建立三个.py文件 1. generateds.py生成数据 ...
- 1 预备知识--Hadoop简介
1 预备知识--Hadoop简介 Hadoop是Apache的一个开源的分布式计算平台,以HDFS分布式文件系统和MapReduce分布式计算框架为核心,为用户提供了一套底层透明的分布式基础设施Had ...
- 给iOS开发新手送点福利,简述UIButton的属性和用法
UIButton属性 1.UIButton状态: UIControlStateNormal // 正常状态 UIControlStateHighlighted // 高 ...
- MySQL 存储配置
- 实现一个最简单的plot函数调用:
实现一个最简单的plot函数调用: 1 import matplotlib.pyplot as plt 2 3 y=pp.DS.Transac_open # 设置y轴数据,以数组形式提供 4 5 x= ...