How to Create Method for Uploading Image in Wcf Service for Using Android Clients

Very often I run across one question flooding in all forums, "How to upload a File using WCF REST Service? ", so I thought let me write a mail on the same.

Essentially, there is nothing specific to practise to upload file, only the below steps

1. Create a service with Postal service functioning

2. Laissez passer file information every bit Input Stream

3. Pass name of the File

4. Host the service in console application [Note : You can host wherever you want though]

Let u.s.a. kickoff create Service Contract.

clip_image002

If you notice above Service contract is creating a REST resources with Mail service method. 1 of the input parameter is Stream.

For your reference, contract interface would look like as below, [Y'all can copyJ]

IService1.cs

            using Organization.ServiceModel; using System.ServiceModel.Web; using System.IO; namespace RESTImageUpload { [ServiceContract] public interface IImageUpload { [OperationContract] [WebInvoke(Method = "Mail", UriTemplate = "FileUpload/{fileName}")] void FileUpload(string fileName, Stream fileStream);  } }        

Once Contract is defined nosotros need to implement service to save a file on sever location.

clip_image004

You need to brand sure you accept a folder FileUpload created on D drive of your server else you would get "Device not set "exception.

Since Write () method takes byte assortment equally input to write data in a file and input parameter of our service is Stream , and so we need to do a conversion between Stream to Bye Array

clip_image006

Concluding Service implementation would look similar below [You can CopyJ]

Service1.svc.cs

            using System.IO; namespace RESTImageUpload {  public class ImageUploadService : IImageUpload {  public void FileUpload(string fileName, Stream fileStream) {  FileStream fileToupload = new FileStream("D:\\FileUpload\\" + fileName, FileMode.Create);  byte[] bytearray = new byte[10000]; int bytesRead, totalBytesRead = 0; do { bytesRead = fileStream.Read(bytearray, 0, bytearray.Length); totalBytesRead += bytesRead; } while (bytesRead > 0);  fileToupload.Write(bytearray, 0, bytearray.Length); fileToupload.Shut(); fileToupload.Dispose();  }  } }        

And then far nosotros are washed with Service definition and implementation and now we demand to host the service. I am going to host service in a panel application. Host programme would have reference of System.ServiceModel and System.ServiceModel.Spider web. If y'all are not able to notice System.ServiceModel.Web reference to add together in your console application then change the target framework to .Cyberspace Framework 4.0 from .Net Framework four.0 client profile.

Programme.cs

            using System; using System.ServiceModel; using RESTImageUpload; using System.ServiceModel.Description;  namespace ConsoleApplication1 { grade Programme { static void Main(string[] args) { cord baseAddress = "http://" + Surroundings.MachineName + ":8000/Service"; ServiceHost host = new ServiceHost(typeof(ImageUploadService), new Uri(baseAddress)); host.AddServiceEndpoint(typeof(IImageUpload), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior()); host.Open(); Console.WriteLine("Host opened"); Console.ReadKey(true); } } }        
Press F5 to run the service hosted in console application.

clip_image008

Service is up and running so allow us call this service to upload the file.

I am creating a simple ASP.Cyberspace Web Application with File Upload control and a push button. ASPX folio looks similar below

Default.aspx

            u<%@ Folio Title="Domicile Page" Language="C#" MasterPageFile="~/Site.main" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>  <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2> Welcome to ASP.Cyberspace! </h2> <p> To learn more about ASP.NET visit <a href="<a href="http://world wide web.asp.net">http://www.asp.internet</a>" title="ASP.NET Website">www.asp.internet</a>. </p> <p> Yous can also find <a href="<a href="http://become.microsoft.com/fwlink/?LinkID=152368&amp;clcid=0x409">http://go.microsoft.com/fwlink/?LinkID=152368&amp;clcid=0x409</a>" championship="MSDN ASP.Net Docs">documentation on ASP.Cyberspace at MSDN</a>. </p> <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="Button1" runat="server" Text="Upload File" /> </asp:Content>        

On click event of button we need to make a call to the service to upload the file.

clip_image010

In above code, I am making a HTTP Web Request and explicitly specifying method is Mail service and content type is text/evidently. Nosotros need to get the Request Stream and write the byte array in that. As HTTP response you can get the status code.

For your reference client code would expect like as beneath,

Default.aspx.cs

using System; using System.Collections.Generic; using System.Linq; using Organisation.Spider web; using Arrangement.Web.UI; using Arrangement.IO; using System.Web.UI.WebControls; using System.Net;  namespace WebApplication1 { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs eastward) { Button1.Click += new EventHandler(Button1_Click); }  void Button1_Click(object sender, EventArgs e) { byte[] bytearray=naught ; string name = ""; //throw new NotImplementedException(); if (FileUpload1.HasFile) { name = FileUpload1.FileName; Stream stream = FileUpload1.FileContent; stream.Seek(0, SeekOrigin.Begin); bytearray = new byte[stream.Length]; int count = 0; while (count < stream.Length) { bytearray[count++] = Convert.ToByte(stream.ReadByte()); }  }  string baseAddress = "http://" + Environs.MachineName + ":8000/Service/FileUpload/"; HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(baseAddress+proper name); request.Method = "Postal service"; asking.ContentType = "text/plain"; Stream serverStream  = asking.GetRequestStream(); serverStream.Write(bytearray, 0, bytearray.Length); serverStream.Close(); using ( HttpWebResponse response = asking.GetResponse() as HttpWebResponse ) { int statusCode =(int) response.StatusCode; StreamReader reader = new StreamReader( response.GetResponseStream() );  }  } } }        

I hope this mail service was useful and saved your time to upload a file. In side by side mail I will prove you how to upload an image from Silverlight client.

schockwhirosed1942.blogspot.com

Source: https://debugmode.net/2011/05/01/uploading-file-to-server-from-asp-net-client-using-wcf-rest-service/

0 Response to "How to Create Method for Uploading Image in Wcf Service for Using Android Clients"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel