Send image as json entry android

后端 未结 4 2219
伪装坚强ぢ
伪装坚强ぢ 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:29

    If you want to include Image in a JSON object which you will be sending in a request, convert Image into Base64 string and put this string into the JSON object.

    For example:

    String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
    

    Check:

    • How to convert a image into Base64 string?
    • Convert png or jpg image to Base64 string in Android
    0 讨论(0)
  • 2021-02-11 09:34

    you have an ImageView

    <ImageView
          android:layout_width = "300dp"
          android:layout_height = "300dp"
          android:id = "@+id/Plaatjeid"
          android:scaleType = "centerCrop"
        android:text = "@string/BerttxtPlaatje"
        android:layout_alignParentEnd="true"
    />
    

    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="<?xml version='1.0'?>";
    mailMessage=mailMessage + "<RiscNotification xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'";
    mailMessage=mailMessage + "xmlns:xsd='htp://www.w3.org/2001/XMLSchema'>";
    mailMessage = mailMessage + "        <mail To>"  + Mailto() + "</mail To>" ;//server7
    mailMessage = mailMessage + "</RiskNotification>";
    

    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, Void, String> {
        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

    <configuration>
      
      <system.web.extensions>
        <scripting>
          <webServices>
            <jsonSerialization maxJsonLength="50000000"/>
          </webServices>
        </scripting>
      </system.web.extensions>  
     <system.web>
    

    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 <head> and the MailBody in the body
            theMessage.Body = "<html>" + StyleText + "<body>" + MailBody + "</body></html>";
    
            // 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

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-=1">
        <meta content="text/html; charset=us-ascii">
        <style>
            h1{color:blue;}
    
            .EditText{
                background:#ff0000;/*rood*/
                height:100;
                font-size:10px;
                color:#0000ff;/*blauw*/
            }
            .EditTextVervolg{
                background:#00cc00;/*groen*/
                font-size:20px;
                color:#ffff00;/*geel*/
            }
        </style>
    </head>
    

    Have fun

    0 讨论(0)
  • 2021-02-11 09:37

    Well, it's kind of experimental, but you can create an array of bytes out of the bitmap, and then create a new string with that array of bytes, and then send it to the server.

    However, why don't you just send a POST request to save the image directly, without any experimental processing or parsing?

    0 讨论(0)
  • 2021-02-11 09:52

    Try base64-encoding the image (like below, where the Uri is your Image - but beware: ImageView has no Getter for the ImageUri, so you have to store it by yourself!):

    Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
    
    ContentResolver cr = getContentResolver();
    InputStream is = cr.openInputStream(uri);
    
    byte[] data = getBytesFromFile(is);
    
    byte[] encoded_data = Base64.encodeBase64(data);
    data_string = new String(encoded_data);
    

    Now you have an base64-encoded String data_string that you can send with your JSON request. On the server-side you just have to decode the String and save the picture.

    0 讨论(0)
提交回复
热议问题