Send image as json entry android

后端 未结 4 2216
伪装坚强ぢ
伪装坚强ぢ 2021-02-11 08:59

I have a requirement where, i am sending a json file to the server and the parsing happens at the server side. I have created the entries to the json file, now i want to store a

4条回答
  •  长发绾君心
    2021-02-11 09:34

    you have an ImageView

    
    

    and in the codebehind

    String plaatje="";
    ImageView iv1 = (ImageView)findViewById(R.id.Plaatjeid);
        iv1.buildDrawingCache();
        Bitmap bitmap = iv1.getDrawingCache();
        ByteArrayOutputStream stream=new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
        byte[] image=stream.toByteArray();
        plaatje = Base64.encodeToString(image, 0);
    

    then you create your Json string

    String mailMessage;
    mailMessage="";
    mailMessage=mailMessage + "";
    mailMessage = mailMessage + "        "  + Mailto() + "" ;//server7
    mailMessage = mailMessage + "";
    

    I have a seperate Class in which I send it Attach the variables to the Class

    GetMethodDemo JsonConnect = new GetMethodDemo();
    JsonConnect.MailTo=  Mailto();
    JsonConnect.Picture=plaatje;
    JsonConnect.bertactivity=this;
    JsonConnect.execute();//staat in AANHET BEGIN
    

    and my Class

        package nl.yentel.finekinney;
        import java.io.BufferedReader;
        import java.io.InputStreamReader;
        import java.io.OutputStream;
        import java.net.HttpURLConnection;
        import java.net.URL;
    
        import android.app.Activity;
        import android.graphics.Bitmap;
        import android.os.AsyncTask;
        import android.view.Gravity;
        import android.widget.Toast;
    
        public class GetMethodDemo extends AsyncTask {
        String MailTo;
        String Picture;
        Activity bertactivity;
        Bitmap bm;
    
         public void BitMapFoto(Bitmap bitmap) {
            bm = bitmap;
        }
    
        //@Override
        protected String doInBackground(String... strings) {
    
              //http://geekonjava.blogspot.com/2014/03/upload-image-on-server-in-android-using.html
    
            String dBresultaat = "start";
            try {
                URL url = new URL("http://10.0.2.2:64489/Risico/Risico.asmx/sendMail");
    
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("POST");
                con.setRequestProperty("Content-Type", "application/json");
                con.setRequestProperty("Accept", "application/json");
                con.setDoOutput(true);
                String jsonInputString = "";
                jsonInputString = "{";
                 jsonInputString = jsonInputString + "\"MailTo\": \"" + MailTo.toString() + "\",";
                jsonInputString = jsonInputString + "\"Picture\": \"" + Picture.toString() + "\""; 
                 //if you take the Picture.toString in debug mode and put it in https://base64.guru/converter/decode/image you see the picture
                  jsonInputString = jsonInputString + "}";
    
                try (OutputStream os = con.getOutputStream()) {
                    byte[] input = jsonInputString.getBytes("utf-8");
                    os.write(input, 0, input.length);
                    int code = con.getResponseCode();
                    System.out.println(code);
    
                    try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
                        StringBuilder response = new StringBuilder();
                        String responseLine = null;
                        while ((responseLine = br.readLine()) != null) {
                            response.append(responseLine.trim());
                        }
                        System.out.println(response.toString());
                        return response.toString();
                    }
    
                } catch (Exception e) {
                    e.printStackTrace();
                    return "catch twee";
                }
            } catch (Exception e) {
                e.printStackTrace();
                return "catch";
            }
        }
    
        @Override
        protected void onPreExecute() {
        }
    
        @Override
        protected void onPostExecute(String s) {
            // super.onPostExecute(s);
            Activity activity = new Bert().activity;
            Toast toast = Toast.makeText(bertactivity, s, Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
            toast.show();
        }
        }
    

    You should have your webservice in Framework 4.0. Framework 3.5 does not work

    and the web.config shows

    
      
      
        
          
            
          
        
        
     
    

    My webmethod looks like this

    [WebMethod()]
    public string sendMail(sstring MailTo, string Picture)
    {      
        string Resultstring = "";
        int i;
        MailMessage theMessage;
        theMessage = new MailMessage();
        // look if there is an attempt to hack the server
        if ((MailBody.ToUpper()).IndexOf("SELECT") > 0 | (MailBody.ToUpper()).IndexOf("UPDATE") > 0)
        {
            Resultstring = "illegal string";
        }
        else
        {
            theMessage.From = new System.Net.Mail.MailAddress(ConfigurationManager.AppSettings["sender"]); // '"no-reply@taakmonitor.nl")
            try
            {
                theMessage.To.Add(new MailAddress(MailFrom)); // also send a mail to the sender
            }
            catch (Exception ex)
            {
                Resultstring = "Mail address "+ MailFrom + " not ok "; //ex.Message; // als het formaat van het mail adres niet goed is
                theMessage = null;
            }
            String FransGetsCopy = WebConfigurationManager.AppSettings["FransGetsCopy"];
    
            String[] ToWhom = NullSafeString(MailTo).Split(',');
            for (i = 0; i <= ToWhom.Length - 1; i++)
            {
                try
                    {
                       theMessage.To.Add(new MailAddress(ToWhom[i]));
                    }
                catch (Exception ex)
                    {
                        Resultstring = Resultstring + " mail address " + ToWhom[i] + " not ok "; //ex.Message; // als het formaat van het mail adres niet goed is
                        theMessage = null;
                     }                
            }
    
            // there should also be a stylesheet
              string StyleText="";
            try
            {
                StyleText = "";
                var data = File.ReadAllText(Server.MapPath("~/App_Data/TextFile.txt"));
                StyleText = data.ToString();   
            }
            catch (Exception)
            {
                Resultstring = Resultstring + " No StyleText available. ";
            }
            theMessage.Subject = MailSubject;
            theMessage.IsBodyHtml = true;
            //the message is created in HTML with the style in the  and the MailBody in the body
            theMessage.Body = "" + StyleText + "" + MailBody + "";
    
            // code copied from
            // https://www.codeproject.com/Tips/569532/Submit-Images-to-Web-Service-and-Get-Them-Back
            //in this piece of code I convert the Json picture data to a picture and attach it to the mail
            try
            {
                byte[] data = Convert.FromBase64String(Picture);
                var stream = new MemoryStream(data, 0, data.Length);
                System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
                stream.Seek(0L, SeekOrigin.Begin);
                theMessage.Attachments.Add(new Attachment(stream, "Picture.png"));
                Resultstring = Resultstring +  " image OK";
            }
            catch (Exception ex)
            {
                Resultstring = Resultstring +  " image not OK";
            } 
            SmtpClient MessageObject = new SmtpClient();
            MessageObject.Host = ConfigurationManager.AppSettings["Host"];
            MessageObject.Port = Int32.Parse(ConfigurationManager.AppSettings["Port"]);
            MessageObject.EnableSsl = false;
            MessageObject.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["Username"], ConfigurationManager.AppSettings["Password"]);
            try
            {
                MessageObject.Send(theMessage);
                Resultstring = Resultstring +  " mail has been send.";
            }
            catch (Exception ex)
            {
                Resultstring = Resultstring +  " mail has NOT been send.";
            }
            MessageObject = null;
            theMessage = null;
        }
        return Resultstring;
    }
    

    at last I have a stylesheet TestFile.txt in the App_data folder attached

    
        
        
        
    
    

    Have fun

提交回复
热议问题