寫在前面
上篇文章介紹了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