写在前面

上篇文章介绍了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 = ; 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的更多相关文章

  1. Restful风格wcf调用4——权限认证

    写在前面 在前面的三篇文章,已经介绍了restful风格wcf,如何实现增删改查以及文件的上传下载操作.本篇文章将介绍一下,调用restful的权限认证的内容.在调用的接口,为了安全,总会需要对请求进 ...

  2. Restful风格wcf调用

    文章:Restful风格wcf调用 作者相当于把wcf服务改造成rest风格. Restful风格wcf调用2——增删改查 这篇文章在第一篇的基础上,进行了优化. Restful风格wcf调用3——S ...

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

    写在前面 上篇文章介绍如何将wcf项目,修改成restful风格的接口,并在上面提供了查询的功能,上篇文章中也感谢园友在评论中的提的建议,自己也思考了下,确实是那个道理.在urltemplate中,定 ...

  4. 构建RESTful风格的WCF服务

    构建RESTful风格的WCF服务 RESTful Wcf是一种基于Http协议的服务架构风格. 相较 WCF.WebService 使用 SOAP.WSDL.WS-* 而言,几乎所有的语言和网络平台 ...

  5. spring boot / cloud (十四) 微服务间远程服务调用的认证和鉴权的思考和设计,以及restFul风格的url匹配拦截方法

    spring boot / cloud (十四) 微服务间远程服务调用的认证和鉴权的思考和设计,以及restFul风格的url匹配拦截方法 前言 本篇接着<spring boot / cloud ...

  6. PHP实现RESTful风格的API实例(二)

    接前一篇PHP实现RESTful风格的API实例(一) Response.php :包含一个Request类,即输出类.根据接收到的Content-Type,将Request类返回的数组拼接成对应的格 ...

  7. PHP实现RESTful风格的API实例(一)

    最近看了一些关于RESTful的资料,自己动手也写了一个RESTful实例,以下是源码 目录详情: restful/ Request.php 数据操作类 Response.php 输出类 index. ...

  8. 用cxf开发restful风格的WebService

    我们都知道cxf还可以开发restful风格的webService,下面是利用maven+spring4+cxf搭建webService服务端和客户端Demo 1.pom.xml <projec ...

  9. Restful风格API接口开发springMVC篇

    Restful风格的API是一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件.它主要用于客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机 ...

随机推荐

  1. vim之YCM配置

    BundleInstall,默认会出现错误 ycm_client_support.[so|pyd|dll] and ycm_core.[so|pyd|dll] not detected; you ne ...

  2. wamp ssl配置https

    主要参考的这个博客 http://blog.csdn.net/sdq4700/article/details/36173665 配置完以后重启wamp , https不能正常访问 apache.log ...

  3. Linux嵌入式内核模块程序设计

    1.环境搭建 vmware+Fedora 2.创建一个Hello文件 [root@localhost ~]# mkdir Hello 3.在Hello里面创建 hello.c 和 Makefile 两 ...

  4. pythonNet day04

    本地套接字 作用:用于本地不同程序间的进行数据传输 本地套接字的创建流程 1.创建套接字对象 sockfd = socket(AF_UNIX,SOCK_STREAM) 2.绑定本地套接字文件,如果文件 ...

  5. setAttribute第三个参数

    object.setAttribute(sName, vValue [, iFlags]) sName参数应是Dom属性而非html中的属性.Dom中Html专有的接口属性应该以小写字母开头,如果属性 ...

  6. urllib2的GET和POST请求(五)

    urllib2默认只支持HTTP/HTTPS的GET和POST方法 urllib.urlencode() urllib 和 urllib2 都是接受URL请求的相关模块,但是提供了不同的功能.两个最显 ...

  7. Shell 函数库

    1.为什么要定义函数库 经常使用的重复代码封装成函数文件 一般不直接执行,而是由其他脚本调用 2.编写一个函数库,该函数库实现以下几个函数. 1.加法函数:add 2.减法函数:reduce 3.乘法 ...

  8. window.addEventListener()/window.postMessage(”text“, '*')

    1.设置监听 window.addEventListener('message', function (msg) { console.log(msg.data);}) 2.发送 message win ...

  9. localStorage,sessionStorage

    h5的本地存储. 现代浏览器普遍开始支持H5本地存储,localStorage.sessionStorage.可以用来代替cookie的一部分存储功能,他比cookie存储量更大.比较实用. 两者用法 ...

  10. [转] 移动平台Html5的viewport使用经验

    转自:http://blog.csdn.net/wuruixn/article/details/8591989 问题描述 web页面采用html5技术实现,在系统登录页面中使用frameset.fra ...