How to upload images to server using MultipartEntityBuilder?

851 views Asked by At

i want to upload image using MultipartEntityBuilder through httpost but it's not uploading.

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

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

builder.addTextBody("firstName", firstname);
builder.addTextBody("lastName", lastname);

if (picture.length()>0) {
    builder.addPart("picture", new FileBody(new File(picture)));
}

Log.d("URL", url);
String credentials = Base64.encodeToString((username+":"+password).getBytes(), Base64.NO_WRAP);

httpPost.setHeader("Authorization", "Basic "+credentials);
httpPost.setHeader("Content-type", "multipart/form-data");

Log.d("BasicAuthorization", credentials);

httpPost.setEntity(builder.build());

Please kindly go through my code and suggest me some solution.

1

There are 1 answers

0
Jignesh Jain On

Try this

   private String fileUpload()
        {
            String strRes = "";
            HttpParams params = new BasicHttpParams();
            params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            mHttpClient = new DefaultHttpClient(params);

            try
            {
                HttpPost httppost = new HttpPost(this.url);
                httppost.addHeader("enctype", "multipart/form-data");

                MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

                File filebody = new File(filepath);
                multipartEntity.addPart("imagepath", new FileBody(filebody));


                httppost.setEntity(multipartEntity);

                HttpResponse response = mHttpClient.execute(httppost);
                // mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
                HttpEntity r_entity = response.getEntity();
                strRes = EntityUtils.toString(r_entity);
                resultCode = 1;
            }
            catch (Exception e)
            {
                e.printStackTrace();
                resultCode = 2;
            }
            return strRes;
        }