how to send image (bitmap) to server in android with multipart-form data json

前端 未结 2 1813
抹茶落季
抹茶落季 2020-12-08 11:51

I have code to upload image to server and it works ,

HttpEntity resEntity;

                HttpClient httpClient = new DefaultHttpClient();
                        


        
相关标签:
2条回答
  • 2020-12-08 12:26
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    

    Then send this encodedImage as a String and in your server you will need to decode it in order to get the image itself.

    0 讨论(0)
  • 2020-12-08 12:35

    *use three library
    1.httpclient-4.3.6
    2.httpcore-4.3.3
    3.httpmime-4.3.6

                byte[] data = null;
                try {    
                    String url = "http://andapp.freetings.in/testbyme.php?";
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost(url); 
                    MultipartEntity entity = new MultipartEntity();
    
                    if(imageBitmap!=null){
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        imageBitmap.compress(CompressFormat.JPEG, 100, bos);
                        data = bos.toByteArray();
                        entity.addPart("uplod_img", new ByteArrayBody(data,"image/jpeg", "test2.jpg"));
                    }
                    // entity.addPart("category", new StringBody(categoryname,"text/plain",Charset.forName("UTF-8")));
                    entity.addPart("category", new StringBody(catid,"text/plain",Charset.forName("UTF-8")));
                    entity.addPart("your_contact_no", new  StringBody(phone,"text/plain",Charset.forName("UTF-8")));
                    entity.addPart("your_emailid", new StringBody(email,"text/plain",Charset.forName("UTF-8")));
                    entity.addPart("your_name", new StringBody(name,"text/plain",Charset.forName("UTF-8")));
    
                    httppost.setEntity(entity);
                    HttpResponse resp = httpclient.execute(httppost);          
                    HttpEntity resEntity = resp.getEntity();
                    String string=EntityUtils.toString(resEntity);
                    //  Log.e("sdjkfkhk", string);
                    return resEntity;
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
    0 讨论(0)
提交回复
热议问题