使用multipart发送多个图像以休息api

时间:2015-06-05 11:53:25

标签: android image-uploading

我这样做是为了上传单张图片。但我想在同一个键上上传多个图像,如5个图像。有人告诉我如何使用multipart

来做到这一点
Json

2 个答案:

答案 0 :(得分:1)

试试此代码,

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;
        }

答案 1 :(得分:0)

尝试以下代码

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;
    // ******************************************************************

}