1

I am developing android application which will upload the image as well as some parameters to the server. From my service side we are using @RequestParam File and @RequestParam getProjectsData as parameters in method in getProjectsData contains all the image details which are stored in the database. Here when i am uploading the image from my android app i am getting an error called HTTP Status 400 - Required request part 'getProjectsData' is not present. Later i had known that i need to send multiple multipart data from my side. Can any one tell me how to post multiple multipart requests one for image upload and another for image properties uploading This is my android app code

AsyncTask<String, Void, String> uploadImageDetails = new AsyncTask<String, Void, String>() {

                    @Override
                    protected void onPreExecute() {
                        super.onPreExecute();
                    }

                    @Override
                    protected String doInBackground(String... urls) {
                        pm_image_details_model pm_img_model = new pm_image_details_model();
                        pm_img_model.setLatitude(String.valueOf(pm_latitude));
                        pm_img_model.setLongitude(String.valueOf(pm_longitude));
                        String result = null;
                        org.apache.http.entity.mime.MultipartEntity reqEntity = new org.apache.http.entity.mime.MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
//                            reqEntity.addPart("getProjectsData", new StringBody(""));
                        bos = new ByteArrayOutputStream();
                        final Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
                        thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        byte[] data = bos.toByteArray();
                        ByteArrayBody bab = new ByteArrayBody(data, "test.jpeg");


                        try {

                            reqEntity.addPart("file", bab);
                            reqEntity.addPart("getProjectsData",new StringBody(json));
                            content = getHttpPutContent(urls[0], reqEntity);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                        return result;
                    }

                    @Override
                    protected void onPostExecute(String s) {
                        super.onPostExecute(s);
                        Log.i("Result from server -->", s);
                    }
                };

HTTP CLIENT

public static String getHttpPutContent(String url, org.apache.http.entity.mime.MultipartEntity multipartEntity) {

        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost put = new HttpPost(url);
            //   put.setHeader("Content-Type", "multipart/form-data");
            //            Log.i(TAG, "Token=> " + token);
            Log.i("-->", "Try to open=> " + url);

            org.apache.http.entity.mime.MultipartEntity reqEntity = multipartEntity;

            put.setEntity(reqEntity);

            HttpResponse httpResponse = httpClient.execute(put);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            Log.i("-->", "Connection code: " + statusCode);

            HttpEntity entity = httpResponse.getEntity();
            String serverResponse = EntityUtils.toString(entity);
            Log.i("-->", "Server response=> " + serverResponse);

            if (!isStatusOk(statusCode))
                return null;

            return serverResponse;

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

1 Answer 1

0

You can send file and data both :

  public MultipartUtility() {

}

public static String getContent(HttpResponse response) throws IOException {
    System.out.println("response code : " + response.getStatusLine().getStatusCode());
    if (response.getStatusLine().getStatusCode() == 200) {
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String body = "";
        String content = "";

        while ((body = rd.readLine()) != null) {
            content += body + "\n";
        }
        return content.trim();
    } else {
        if (response.getStatusLine().getStatusCode() == 401) {
            return Constants.UnAuthorized;
        } else {
            return "Error";
        }
    }
}
   // here fileName means path of file.
public String postFile(String fileName, String body) throws Exception {

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(Your Api is here);

    HttpParams params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 30000);
    HttpConnectionParams.setSoTimeout(params, 30000);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    if (fileName != null) {

        final File file = new File(fileName);
        FileBody fb = new FileBody(file);
        builder.addPart("file", fb);
        builder.addPart("photoCaption", new StringBody(body));
    }

    final HttpEntity yourEntity = builder.build();

    class ProgressiveEntity implements HttpEntity {
        @Override
        public void consumeContent() throws IOException {
            yourEntity.consumeContent();
        }

        @Override
        public InputStream getContent() throws IOException,
                IllegalStateException {

            return yourEntity.getContent();
        }

        @Override
        public Header getContentEncoding() {
            return yourEntity.getContentEncoding();
        }

        @Override
        public long getContentLength() {
            return yourEntity.getContentLength();
        }

        @Override
        public Header getContentType() {
            return yourEntity.getContentType();
        }

        @Override
        public boolean isChunked() {
            return yourEntity.isChunked();
        }

        @Override
        public boolean isRepeatable() {
            return yourEntity.isRepeatable();
        }

        @Override
        public boolean isStreaming() {
            return yourEntity.isStreaming();
        } // CONSIDER put a _real_ delegator into here!

        @Override
        public void writeTo(OutputStream outstream) throws IOException {

            class ProxyOutputStream extends FilterOutputStream {
                /**
                 * @author Stephen Colebourne
                 */

                public ProxyOutputStream(OutputStream proxy) {
                    super(proxy);
                }

                public void write(int idx) throws IOException {
                    out.write(idx);
                }

                public void write(byte[] bts) throws IOException {
                    out.write(bts);
                }

                public void write(byte[] bts, int st, int end) throws IOException {
                    out.write(bts, st, end);
                }

                public void flush() throws IOException {
                    out.flush();
                }

                public void close() throws IOException {
                    out.close();
                }
            } // CONSIDER import this class (and risk more Jar File Hell)

            class ProgressiveOutputStream extends ProxyOutputStream {
                public ProgressiveOutputStream(OutputStream proxy) {
                    super(proxy);
                }

                public void write(byte[] bts, int st, int end) throws IOException {

                    // FIXME  Put your progress bar stuff here!

                    out.write(bts, st, end);
                }
            }

            yourEntity.writeTo(new ProgressiveOutputStream(outstream));
        }
    }
    ;
    ProgressiveEntity myEntity = new ProgressiveEntity();

    post.setEntity(myEntity);
    HttpResponse response = client.execute(post);

    return getContent(response);

}

}

call this class like below :

  new MultipartUtility().postFile(filepath, body);

pass file path here and pass parameter as a body.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.