Sending JSON data and Image to Server

I'm not sure if I'm taking the correct course in trying to achieve my objective.

I'm trying to send both JSON data and an image to a server. When the user clicks on a button the async call activates, gathers the JSON container that has the data and gets the image path. Here's is what I have so far:

protected String doInBackground(String... data) {
            gatherEditTextStringValue();

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);

            try {
                ArrayList<NameValuePair> postVars = new ArrayList<NameValuePair>();
                postVars.add(new BasicNameValuePair("JSON", String.valueOf(JSONMainContainer)));
                httppost.setEntity(new UrlEncodedFormEntity(postVars));

                if (questionTitleImageUri != null) {
                    questionTitleImageFile = new File(getRealPathFromURI(questionTitleImageUri));
                    FileBody bin1 = new FileBody(questionTitleImageFile);
                    MultipartEntity reqEntity = new MultipartEntity();
                    reqEntity.addPart("uploadedfile1", bin1);
                    httppost.setEntity(reqEntity);
                }

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            try {
                HttpResponse response = httpclient.execute(httppost);
                responseBody = EntityUtils.toString(response.getEntity());
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return responseBody;
        }

Now the problem is that I can send either or, not both. Is there a way to append the image data to the setEntity so that its aggregates both of them? Thank ye.

Upvotes: 1

Views: 758

Answers (1)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132972

Add both parameters to MultipartEntity instead of calling setEntity two times because second call of setEntity method will override first method call settings do it as:

MultipartEntity reqEntity = new MultipartEntity();
// add file
reqEntity.addPart("uploadedfile1", bin1);
// add JSON String 
reqEntity.addPart("JSON", new StringBody(String.valueOf(JSONMainContainer)));
httppost.setEntity(reqEntity);

Upvotes: 2

Related Questions