1

I am trying to upload an image with some data, like i want to send data in key-value format:

(Key is image)- {"image", Image} (key is username)- {"username", "abc@abc.com"}

But here for uploading image server side coding is used "Multipart", can anyone suggest me how can i send image in multipart format with this key- value json format?

This is my application:

String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "xxxxxxxx";
String EndBoundary = "";

String str = twoHyphens + boundary + lineEnd;
String str2 = "Content-Disposition: form-data; name=\"username\"";
String str3 = "abc@abc.com";
String str4 = "Content-Disposition: form-data; name=\"imgName\"";
String str5 = "Content-Type: image/jpeg";
String str6 = twoHyphens + boundary + twoHyphens;

StrTotal = str + str2 + "\r\n" + str3 + "\r\n" + str
            + str4 + "\r\n" + str5 + "\r\n"+"\r\n"+ encodedImage + "\r\n" + str6;

This is multipart side code, now i want to send this from json format to server.

List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("username", "abc@abc.com"));
param.add(new BasicNameValuePair("image", ???));

And this param value to server, but how to send that multipart data with this?

  • Take a look here: http://stackoverflow.com/questions/27579519/how-to-upload-image-to-server-using-multipart-entity – Dan Cantir Feb 29 '16 at 11:06
  • Possible duplicate of [How to upload multipart form data and image to server in android?](http://stackoverflow.com/questions/19026256/how-to-upload-multipart-form-data-and-image-to-server-in-android) – Farhad Feb 29 '16 at 11:07

1 Answers1

1

You can do something like this

    public void uploadUserPhoto(File image) {

    try {

        HttpPost httppost = new HttpPost("some url");

        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
        multipartEntity.addPart("Title", new StringBody("Title"));
        multipartEntity.addPart("Nick", new StringBody("Nick"));
        multipartEntity.addPart("Email", new StringBody("Email"));
        multipartEntity.addPart("Description", new StringBody(Settings.SHARE.TEXT));
        multipartEntity.addPart("Image", new FileBody(image));
        httppost.setEntity(multipartEntity);

        mHttpClient.execute(httppost, new PhotoUploadResponseHandler());

    } catch (Exception e) {
        Log.e(ServerCommunication.class.getName(), e.getLocalizedMessage(), e);
    }
}
Vivek Mishra
  • 5,669
  • 9
  • 46
  • 84