Android : upload Image and JSON using MultiPartEntityBuilder

后端 未结 3 1670
说谎
说谎 2020-12-09 05:19

I try to upload data to server, my data containing multiple images and large JSON, before it, I Try to send with convert image to string using base64

相关标签:
3条回答
  • 2020-12-09 06:07
        Log.d(LOG_SERVICE_TAG, "Sending Multipart Image with Json data"+");      
        InputStream imageStream;
        JSONObject objResult;
        boolean bSucess = true;
                // Base 64 image string was stored with image object , 
        String imageBase64 = image.getImageString();
        // This base64 to byte , One can directly read bytes from file from Disk
        String imageDataBytes = imageBase64.substring( imageBase64.indexOf(",")+1);
        HttpClient client = null;
        HttpPost post = null;
        HttpResponse response = null;
        HttpEntity httpEntity = null;
        String result;
        imageStream = new ByteArrayInputStream(Base64.decode(imageDataBytes.getBytes(), Base64.DEFAULT));   
        try{
            //Forming Json Object 
            JSONObject jsonImageMetdata = new JSONObject();     
            JSONObject objMultipart = new JSONObject();     
            try {
                objMultipart.put("param1", "param 1 value");
                objMultipart.put("param2",  "param 2 value"  );
                objMultipart.put("param3","param 3 value" );
                objMultipart.put("param4", "param 4 value");                
                jsonImageMetdata.put("MultipartImageMetadata", objMultipart);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // converting json data to string
            String strImageMetadata = jsonImageMetdata.toString();
            client = new DefaultHttpClient();
            post = new HttpPost("https://abcd");
            MultipartEntityBuilder entityBuilder = null;
            try{
                entityBuilder = MultipartEntityBuilder.create();
            }
            catch(Exception a){
                Log.d("name",a.getMessage());
                throw a;                
            }
            entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);    
    
            // adding text
            entityBuilder.addTextBody("dummyParameter","Dummy text",ContentType.TEXT_PLAIN);             
    
            // adding Image
            if(imageStream != null){                
                entityBuilder.addBinaryBody("file", imageStream,ContentType.create("image/jpeg"),"imagename.jpg");
            }         
    
            // sending formed json data in form of text
            entityBuilder.addTextBody("descriptions", strImageMetadata, ContentType.APPLICATION_JSON) ;
            HttpEntity entity = entityBuilder.build();
            post.setEntity(entity);         
            response = client.execute(post);
            httpEntity = response.getEntity();
            result = EntityUtils.toString(httpEntity);
    

    Download httpcore-4.3.2.jar , httpmime-4.3.3.jar from Apache and add them in lib folder of Android project for using MultipartEntityBuilder

    0 讨论(0)
  • 2020-12-09 06:08

    There is my solution, for sending images and text fields (with apache http libraries) with POST request. Json could be added in the same way, as my fields group and owner.

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                byte[] imageBytes = baos.toByteArray();
    
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(StaticData.AMBAJE_SERVER_URL + StaticData.AMBAJE_ADD_AMBAJ_TO_GROUP);
    
                String boundary = "-------------" + System.currentTimeMillis();
    
                httpPost.setHeader("Content-type", "multipart/form-data; boundary="+boundary);
    
                ByteArrayBody bab = new ByteArrayBody(imageBytes, "pic.png");
                StringBody sbOwner = new StringBody(StaticData.loggedUserId, ContentType.TEXT_PLAIN);
                StringBody sbGroup = new StringBody("group", ContentType.TEXT_PLAIN);
    
                HttpEntity entity = MultipartEntityBuilder.create()
                        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                        .setBoundary(boundary)
                        .addPart("group", sbGroup)
                        .addPart("owner", sbOwner)
                        .addPart("image", bab)
                        .build();
    
                httpPost.setEntity(entity);
    
                try {
                    HttpResponse response = httpclient.execute(httpPost);
                    ...then reading response
    
    0 讨论(0)
  • 2020-12-09 06:17

    To send binary data you need to use addBinaryBody method of MultipartEntityBuilder. Sample of attaching:

    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.mime.MultipartEntityBuilder;
    //Image attaching
    MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
    File file;
    multipartEntity.addBinaryBody("someName", file, ContentType.create("image/jpeg"), file.getName());
    //Json string attaching
    String json;
    multipartEntity.addPart("someName", new StringBody(json, ContentType.TEXT_PLAIN));
    

    Then make request as usual:

    HttpPut put = new HttpPut("url");
    put.setEntity(multipartEntity.build());
    HttpResponse response = client.execute(put);
    int statusCode = response.getStatusLine().getStatusCode();
    
    0 讨论(0)
提交回复
热议问题