简体   繁体   中英

sending multiple images to rest api using multipart

I did this for uploading single image . But i want upload multiple image like 5 images in same key. Anyone tell me how to do it using multipart

HttpPost post = new HttpPost(SIGNUP_URL);
            MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            ContentBody body=new FileBody(new File(obj.getBannerPath()),"image/*");
            multipartEntity.addPart(KEY_BANNER, body);
            multipartEntity.addPart(KEY_BUSINESS_NAME,new StringBody(obj.getBusinessName()));
            multipartEntity.addPart(KEY_DESCRIPTION,new StringBody(obj.getDescription()));
            multipartEntity.addPart(KEY_ADDRESS,new StringBody(obj.getAddress()));

post.setEntity(multipartEntity);

            response=client.execute(post);

Try this Code,

HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 60000); // 1 min
HttpConnectionParams.setSoTimeout(httpParams,60000); // 1 min

HttpClient client = new DefaultHttpClient(httpParams);
//
// HttpPost post = new
//HttpPost("ex.php/my_api/my_service_api_test/event_user_data");
HttpPost post = new HttpPost(AppConstants.URL_BASE + "event_user_data");
MultipartEntity entity = new MyMultipartEntity(new ProgressListener() {

                @Override
                public void transferred(long num) {
                    // TODO Auto-generated method stub

                    publishProgress((int) ((num / (float) totalSize) *100));
                }
            });
            boolean datacomplete=false;
            try {

                JSONArray array = new JSONArray();
                JSONObject text = new JSONObject();
                text.put("event_main_id",Session.GetInstance(getApplicationContext()).GetEventId());
                text.put("event_title", Session.GetInstance(getApplicationContext()).getUserDetail().getUserfname());
                text.put("event_detail", "");
                text.put("event_privacy", "public");

                FileBody fileBody;
                if (posttype.equals("image")) {
                    text.put("post_type", posttype);
                    File myFile2 = new File(postpath);
                    fileBody = new FileBody(myFile2, "image/jpeg");
                    entity.addPart("image", fileBody);
                    // }
                } else {
                    text.put("post_type", posttype);
                    File myFile = new File(postpath);
                    fileBody = new FileBody(myFile, "video/mp4");
                    entity.addPart("video", fileBody);

                    File myFile2 = new File(postpaththumb);
                    FileBody fileBody2 = new FileBody(myFile2, "image/jpeg");
                    entity.addPart("video_thumb", fileBody2);
                }

                text.put("post_userid", Session.GetInstance(getApplicationContext()).getUserDetail().getUserid());
                text.put("post_username", Session.GetInstance(getApplicationContext()).getUserDetail().getUserfname());
                text.put("post_comment", postcomment);
                text.put("post_privacy", postprivacy);
                text.put("post_tagging", posttages);
                text.put("post_mood", postmood);

                // if (mGPS.canGetLocation) {
                text.put("post_lat", LocationService.getLat());
                text.put("post_long", LocationService.getLong());
                text.put("post_location", LocationService.GetMysubAddress(MainActivity.this));
                // } else {
                // text.put("post_lat", "22.25");
                // text.put("post_long", "75.25");
                // text.put("post_location", "NA");
                // }

                array.put(text);
                entity.addPart("data", new StringBody(array.toString()));
                datacomplete=true;
            } catch (Exception exception) {
                return null;
            }
            // List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            if(datacomplete)
            {
                totalSize = entity.getContentLength();
                post.addHeader("user_id", Session.GetInstance(MainActivity.this).getUserDetail().getUserid());
                post.addHeader("device_id", MainActivity.GetDeviceId(MainActivity.this).toString());
                post.addHeader("device_type", "android");
                post.setEntity(entity); // as UTF-8
                try {
                    HttpResponse response = client.execute(post);
                    HttpEntity httpEntity = response.getEntity();
                    is = httpEntity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();
                    //System.out.println(sb.toString());

                    // try parse the string to a JSON object
                    try {
                        jObj = new JSONObject(sb.toString());
                    } catch (JSONException e) {
                        Log.e("JSON Parser", "Error parsing data " + e.toString());
                    }

                    return jObj;
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            return null;
        }

Try Folllowing code

protected WebserviceResultData doInBackground(Void... params) {
    Object resultObject = null;
    WebserviceResultData webserviceResultData = null;

    // ******************************************************************
    try {

        // Create the POST object
        HttpPost post = new HttpPost(webServiceData.serverUrl);

        // ********************************************************************************************************************

        // Create the multipart entity object and add a progress listener
        // this is a our extended class so we can know the bytes that have
        // been transfered
        MultipartEntity entity = new MyMultipartEntity(new ProgressListener() {
            @Override
            public void transferred(long num) {
                publishProgress((int) ((num / (float) totalSize) * 100));
                Log.d("DEBUG", num + " - " + totalSize);

            }
        });
        // Add the file to the content's body
        ContentBody cbFile = null;
        for (int i = 0; i < strImagePath.size(); i++) {
            File file = new File(strImagePath.get(i));
            cbFile = new FileBody(file, "image/jpeg");

            entity.addPart("source", cbFile);
        }
        // entity.addPart("source", cbFile);

        // After adding everything we get the content's lenght
        totalSize = entity.getContentLength();

        // We add the entity to the post request
        post.setEntity(entity);

        // Execute post request
        HttpResponse response = client.execute(post);
        // int statusCode = response.getStatusLine().getStatusCode();

        String resObj = EntityUtils.toString(response.getEntity());

        if (resObj != null) {
            Logger.logger("===============================================");
            Logger.logger("Responce---------", "" + resObj.toString());
            Logger.logger("===============================================");
            resultObject = getParsedResponse(resObj, webServiceData.parsedClass);
            webserviceResultData = new WebserviceResultData(resultObject, webServiceData);
        }

        return webserviceResultData;

    } catch (ClientProtocolException e) {
        // Any error related to the Http Protocol (e.g. malformed url)
        e.printStackTrace();
    } catch (IOException e) {
        // Any IO error (e.g. File not found)
        e.printStackTrace();
    }

    return null;
    // ******************************************************************

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM