Friday 27 February 2015

.Net WebMethod for Uploading Picture


It is often necessary to upload pictures/video from Android app to server. If you are working with .Net Web service/API in Android app. Then you need to write a web method in your .Net web service for uploading picture(s).
From Android app, you send image encoded as Base64 String to web service. The web method receives the encoded Base64 String and perform necessary manipulation to save and upload pictures.

Here is webmethod code.

[WebMethod]
    [SoapHeader("Authentication")]      //--Authentication Header- if necessary
    public String saveImage(string encodedData, string image_name)
    {
        EventLog.WriteLog("-------------------------Start Time:  " + DateTime.Now.ToString() + "-----------------------savePicture--");//write log for tracing
        String result = null;
        try
        {
            if (encodedData != null && encodedData != "")
            {

                //EventLog.WriteLog("-------------------------Encoded Data:\n  " + encodedData + "-----------------------savePicture--");
                // Convert Base64 String to byte[]
                byte[] imageBytes = Convert.FromBase64String(encodedData);
                Stream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
                                
                // Convert byte[] to Image
                ms.Write(imageBytes, 0, imageBytes.Length);
               
                Image image = Image.FromStream(ms, true);
                //string path = @"G:\Pictures\";
                              
                String imageName = image_name + ".png";
                //path += imageName;

                result = UploadFile(imageBytes, imageName);                
            }
            return result;
        }
        catch (Exception ex)
        {
            string sClientLog = System.Environment.NewLine + DateTime.Now.ToString().PadRight(30, ' ') + ex.Message + ", " + ex.StackTrace;
            EventLog.WriteLog("Application-Name:" + sClientLog);//write exception in log for error tracing
            return "Picture not Saved\nPlease Try Again";
        }
        finally
        {
            EventLog.WriteLog("-------------------------End Time:  " + DateTime.Now.ToString() + "-----------------------savePicture--");           
        }
    }

    private String UploadFile(byte[] image , string fileName)
    {
        try
        {
            EventLog.WriteLog("-------------------------UploadFile:\n  " + fileName + "-----------------------Uploading Picture--");
            //FileInfo toUpload = new FileInfo(fileName);
            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://IP-Address/Folder/Pictures/" + "/" + fileName);//Create a folder for pictures
            request.Method = WebRequestMethods.Ftp.UploadFile;
            // request.Credentials = new NetworkCredential("anonymous", "write your email address here");
            Stream ftpStream = request.GetRequestStream();
            //FileStream file = File.OpenRead(fileName);
            int length = 1024;
            byte[] buffer = new byte[image.Length];
            int bytesRead = 0;

            for (int i = 0; i < image.Length; i += length)
            {
                try
                {
                    if (bytesRead + 1024 > image.Length)
                    {
                        int remLength = image.Length - bytesRead;

                        byte[] buffer2 = new byte[remLength];

                        Buffer.BlockCopy(image, i, buffer2, 0, remLength);

                        bytesRead += remLength;

                        ftpStream.Write(buffer2, 0, remLength);
                    }
                    else
                    {
                        Buffer.BlockCopy(image, i, buffer, 0, length);

                        bytesRead += length;

                        ftpStream.Write(buffer, 0, length);
                    }
                }
                catch (Exception ex)
                {
                    EventLog.WriteLog("-----------------Exception:\n" + ex.Message.ToString() + "-----------------------Exception--");
                    return "Picture not Saved\nPlease Try Again.";//write exception in log for error tracing
                }
            }

This is all about uploading pictures through web method of .Net web service.
Please don't forget to ask if you are facing difficulty in implementing this post. Your valuable suggestions are highly appreciated and please correct me if I am doing something wrong in this post.

Thank you

No comments:

Post a Comment