Saturday 9 February 2013

Image uploading through REST API in wcf

Image can be uploaded in byte form in database through image streaming. Here I have pasted a wcf code that will save image in byte form in database. Image should be posted in stream form on service.

WCF:

Interface(contract):

   [ServiceContract]
    public interface IAPIService
    {
        [OperationContract]              
        [WebInvoke(ResponseFormat = WebMessageFormat.Json,
 UriTemplate = "PostImage", Method = "POST")]
        string PostImage(Stream sm);
        
    } 

Service file (svc):

 public class APIService : IAPIService
    { 

      public string PostImage(Stream sm)
         {
           System.Drawing.Bitmap imag = new System.Drawing.Bitmap(sm);
           byte[] imagedata = ImageToByte(imag);
            //Write code here to Save byte code to database..
          return "success";
        }

       public static byte[] ImageToByte(System.Drawing.Image img)
        {
           
            ImageConverter converter = new ImageConverter();
            return (byte[])converter.ConvertTo(img, typeof(byte[]));
        }
   }

Client Side Code:


public void PostData()
    {
        try
        {
             byte[] fileToSend = null;
        string name = "";
        
        if (FileUpload1.HasFile)
        {
            name = FileUpload1.FileName;
            Stream stream = FileUpload1.FileContent;
            stream.Seek(0, SeekOrigin.Begin);
            fileToSend = new byte[stream.Length];
            int count = 0;
            while (count < stream.Length)
            {
                fileToSend[count++] = Convert.ToByte(stream.ReadByte());
            }
            
        }

        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create 
                       ("www.abc.com/APIService.svc/PostImage");
      
        req.Method = "POST";
        req.ContentType = "application/octet-stream";
        req.ContentLength = fileToSend.Length;
        Stream reqStream = req.GetRequestStream();
        reqStream.Write(fileToSend, 0, fileToSend.Length);
        reqStream.Close();

        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

        StreamReader reader = new StreamReader(resp.GetResponseStream());

        string result = reader.ReadToEnd();
        }
        catch (Exception ex)
        {
            
            throw ex;
        }
    }

No comments:

Post a Comment