Write in front
The previous article introduced the RESTful interface to add and delete changes, this article will introduce, how to upload and download files through the data stream.
Series Articles
RESTful style WCF calls
RESTful style WCF calls 2--additions and deletions
An example
Add a WCF service, register the route in Global.asax, and modify the token of the Svc file to add the factory attribute.
// Registering Routes SYSTEM.WEB.ROUTING.ROUTETABLE.ROUTES.ADD (new System.ServiceModel.Activation.ServiceRoute ( "imageservice"newtypeof(ImageService));
<%@ ServiceHost language="C #" debug="true" service=" Wolfy.WCFRestfuleDemo.ImageService" codebehind="ImageService.svc.cs " factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
Contract
namespacewolfy.wcfrestfuledemo{//note:you can use the ' Rename ' command on the ' Refactor ' menu to change the interface name ' Iimageservice ' in both Co De and config file together.[ServiceContract] Public InterfaceIimageservice {/// <summary> ///get the file stream based on the relative path of the picture/// </summary> /// <param name= "Imgurl" ></param> /// <returns></returns>[OperationContract] [WebGet (UriTemplate="Api/{imagurl}")] Stream Getimagestream (stringImgurl); /// <summary> ///Upload Image/// </summary> /// <param name= "Imgstream" ></param> /// <param name= "ImageName" ></param>[OperationContract] [WebInvoke (UriTemplate="Api/{imagename}", Method ="POST")] voidUploadimage (Stream Imgstream,stringimageName); /// <summary> ///get the relative path of all pictures/// </summary> /// <returns></returns>[OperationContract] [WebGet (UriTemplate="api/list", Responseformat =Webmessageformat.xml)]string[] getimages (); }}
Realize
usingSystem;usingSystem.Collections.Generic;usingSystem.Drawing;usingSystem.IO;usingSystem.Linq;usingSystem.Runtime.Serialization;usingSystem.ServiceModel;usingSystem.ServiceModel.Web;usingSystem.Text;namespacewolfy.wcfrestfuledemo{//note:you can use the ' Rename ' command on the ' Refactor ' menu to change the class name ' ImageService ' in code, SVC an d config file together. //note:in order to launch WCF Test Client for testing the This service, please select Imageservice.svc or imageservice.sv C.cs at the solution Explorer and start debugging. Public classImageservice:iimageservice {/// <summary> ///get the file stream based on the relative path of the picture/// </summary> /// <param name= "Imgurl" ></param> /// <returns></returns> PublicSystem.IO.Stream Getimagestream (stringImgurl) { varContentType = Path.getextension (Imgurl). Trim ('.'); Weboperationcontext WOC=weboperationcontext.current; //dynamically set contenttype based on the requested picture typeWoC. Outgoingresponse.contenttype ="image/"+ContentType; stringSavepath = System.Web.HttpContext.Current.Server.MapPath ("/images"); stringFilePath =Path.Combine (Savepath, Imgurl); returnFile.openread (FilePath); } /// <summary> ///Upload Image/// </summary> /// <param name= "Imgstream" ></param> /// <param name= "ImageName" ></param> Public voidUploadimage (System.IO.Stream Imgstream,stringimageName) { vardir = System.Web.HttpContext.Current.Server.MapPath ("~/images"); varFile =Path.Combine (dir, imageName); varBitmap =Bitmap.fromstream (Imgstream); Bitmap. Save (file); } /// <summary> ///get the relative path of all pictures/// </summary> /// <returns></returns> Public string[] GetImages () {List<string> lstimages =Newlist<string>(); vardir = System.Web.HttpContext.Current.Server.MapPath ("~/images"); string[] paths =Directory.GetFiles (dir); for(inti =0; I < paths. Length; i++) {Lstimages.add (paths[i]. Replace (dir,"")); } returnLstimages.toarray (); } }}
First, upload the file 1.jpg
Try { varHttpClient =NewHttpClient (); varStrposturl ="http://localhost:21074/imageservice/api/{0}"; stringFileName = Path.getfilename ("1.jpg"); FileStream FS=NewFileStream ("1.jpg", FileMode.Open, FileAccess.Read, fileshare.readwrite); Httpresponsemessage Response= Httpclient.post (string. Format (Strposturl, FileName), Httpcontent.create (FS)); Fs. Dispose (); Console.WriteLine ("Upload Successful"); } Catch(Exception) {Throw; }
Client prompt
To view the images directory, 1.jpg has been uploaded successfully.
viewing in a browser through restful services: sending a GET request in a browser will call the Getimagestream method, which will respond to the browser and render the stream.
There is one last interface test that returns all the pictures. Because WCF hosts a Web site, it can also be called directly in the browser, which will return the XML information of the relative paths of all the pictures and display them on the page.
Summarize
This article describes how the restful interface handles the stream that is posted, and how to return the stream to the client, which is also a way to upload a download file.
Resources
http://blog.csdn.net/fangxing80/article/details/6261431
RESTful style WCF calls 3--stream