Best method to send image and a text from android

2019-06-14 15:54发布

I need to send an image and text from android to wcf service, tried with http client with multipart but no luck, kindly suggest.

1条回答
Melony?
2楼-- · 2019-06-14 16:20

send image using multipartBuilder and send text separately as json via http url connection, the below code for sending image to wcf service is this Android code

public  String postFiless( byte[] imgbyt, String urlString) throws Exception {

            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(urlString);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();        
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);         
            byte[] data =  imgbyt;     
            String fileName = String.format("File_%d.jpg",new Date().getTime());
            ByteArrayBody bab = new ByteArrayBody(data, fileName);
            builder.addPart("image", bab);        
            final HttpEntity entity = builder.build();
            post.setEntity(entity );
            HttpResponse response = client.execute(post);     

            Log.e("result code", ""+response.getStatusLine().getStatusCode());

            return getContent(response);

        } 
public static String getContent(HttpResponse response) throws IOException {
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String body = "";
            String content = "";
            while ((body = rd.readLine()) != null) 
            {
                content += body + "\n";
            }
            return content.trim();
        }

WCF CODE TO GET THE IMAGE STREAM SENT FROM ANDROID Three steps to upload image using Multipart Parser from android to WCF Rest Service

//Step 1
//WCF Rest Interface
// Namespace
using System.IO;
[OperationContract]
[WebInvoke(Method = "POST",  ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, UriTemplate = "/UploadImg")]
string UploadImg(Stream fileStream);
Step 2
// WCF Implementation class
// Name spaces
using System.IO;
public string UploadImg(Stream fileStream)        {
            string strRet = string.Empty;
            string strFileName = AppDomain.CurrentDomain.BaseDirectory + "Log\\"; // System.Web.Hosting.HostingEnvironment.MapPath("~/Logs/");
            string Path = HttpContext.Current.Server.MapPath("~/Photos");// System.Web.Hosting.HostingEnvironment.MapPath("~/Photos/");// HttpContext.Current.Server.MapPath("~/Photos/")
            try            {
               MultipartParser parser = new MultipartParser(fileStream);        
                if (parser.Success)  {
                    string fileName = parser.Filename;
                    string contentType = parser.ContentType;
                    byte[] fileContent = parser.FileContents;
                    Encoding encoding = Encoding.UTF8;
                    FileStream fileToupload = new FileStream(Path + "/" + fileName, FileMode.Create);
                    fileToupload.Write(fileContent, 0, fileContent.Length);
                    fileToupload.Close();
                    fileToupload.Dispose();
                    fileStream.Close(); 
                    strRet= fileName;
                }                else                {
                    return "Image Not Uploaded";
                }            }
            catch (Exception ex)           {
                // handle the error
            }
            return strRet;
        }
Step 3
// MultipartParser class
//Namespace
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
public class MultipartParser    {
         public IDictionary<string, string> Parameters = new Dictionary<string, string>();
         public MultipartParser(Stream stream)        {
            this.Parse(stream, Encoding.UTF8);
        }
        public MultipartParser(Stream stream, Encoding encoding)        {
            this.Parse(stream, encoding);
        }
        public string getcontent(Stream stream, Encoding encoding)        {
            // Read the stream into a byte array
            byte[] data = ToByteArray(stream);
            // Copy to a string for header parsing
            string content = encoding.GetString(data);
            string delimiter = content.Substring(0, content.IndexOf("\r\n"));
            string[] sections = content.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string s in sections)       {
                Match nameMatch = new Regex(@"(?<=name\=\"")(.*?)(?=\"")").Match(s);
                string name = nameMatch.Value.Trim().ToLower();
                if (!string.IsNullOrWhiteSpace(name))        {
                    int startIndex = nameMatch.Index + nameMatch.Length + "\r\n\r\n".Length;    
                }            
}
            string strRet = ""; //Parameters["name"];
            return strRet;
        }
        private void Parse(Stream stream, Encoding encoding)        {
            this.Success = false;
            // Read the stream into a byte array
            byte[] data = ToByteArray(stream);
            // Copy to a string for header parsing
            string content = encoding.GetString(data);
            // The first line should contain the delimiter
            int delimiterEndIndex = content.IndexOf("\r\n");
            if (delimiterEndIndex > -1)    {
                string delimiter = content.Substring(0, content.IndexOf("\r\n"));
                // Look for Content-Type
                Regex re = new Regex(@"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)");
                Match contentTypeMatch = re.Match(content);
                // Look for filename
                re = new Regex(@"(?<=filename\=\"")(.*?)(?=\"")");
                Match filenameMatch = re.Match(content);
                //re = new Regex(@"(?<=name\=\"")(.*?)(?=\"")");
                //Match nameMatch = re.Match(content);
                // Did we find the required values?
                if (contentTypeMatch.Success && filenameMatch.Success)    {
                    // Set properties
                    this.ContentType = contentTypeMatch.Value.Trim();
                    this.Filename = filenameMatch.Value.Trim();
                    // Get the start & end indexes of the file contents
                    int startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;
                    byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
                    int endIndex = IndexOf(data, delimiterBytes, startIndex);
                    int contentLength = endIndex - startIndex;
                    // Extract the file contents from the byte array
                    byte[] fileData = new byte[contentLength];
                    Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);
                    this.FileContents = fileData;
                    this.Success = true;                }
            }        }
        private int IndexOf(byte[] searchWithin, byte[] serachFor, int startIndex)       {
            int index = 0;
            int startPos = Array.IndexOf(searchWithin, serachFor[0], startIndex);
            if (startPos != -1)          {
                while ((startPos + index) < searchWithin.Length)             {
                    if (searchWithin[startPos + index] == serachFor[index])                   {
                        index++;
                        if (index == serachFor.Length)                        {
                            return startPos;
                        }
                    }    else      {
                        startPos = Array.IndexOf<byte>(searchWithin, serachFor[0], startPos + index);
                        if (startPos == -1)      {
                           return -1;
                        }
                        index = 0;
                    }
                }
            }
            return -1;
        }
        private byte[] ToByteArray(Stream stream)        {
            byte[] buffer = new byte[32768];
            using (MemoryStream ms = new MemoryStream())           {
                while (true)       {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                        return ms.ToArray();
                    ms.Write(buffer, 0, read);
                }
            }
        }
        public bool Success        {
            get;
            private set;
        }
        public string ContentType        {
            get;
            private set;
        }
        public string Filename        {
            get;
            private set;
        }
        public byte[] FileContents        {
            get;
            private set;
        }
        public string Imgname        {
            get;
            private set;
        }    }
// End of Wcf rest Service Code
查看更多
登录 后发表回答