Uploading Images to Server Android

android efficient way to upload image to server

My 2 cents:

Few things can be improved depending on what you are targeting.

  1. If you are worried about the data usage, then you can decrease the size of the image before uploading. Now a days for the newer phone models, the picture resolutions are very high. You can alter the size of the image on the device itself before uploading. Eg: How to resize image (Bitmap) to a given size? and Decrease image size without losing its quality in android
  2. If you are worried about blocking user when the images are uploading:

    • Do the uploading part in the background, so that you don't block the user from doing anything.
    • Also as suggested in comments you can do a multi-part upload so that in case something goes wrong with the upload, you don't have to upload the whole thing again.
  3. If you are only worried about the time taken to upload:

    • You either need a better network connectivity or lower the image size. If you know most of your users will be in lower connectivity areas, then it might be fine to decrease size.
    • You can use some library like Facebook's Network Connection
      Quality Checker
      Class to check
      the current network quality when trying to upload and maybe wait for
      a good quality network before uploading.
    • You can choose to only upload on wi-fi and use BroadcastReceiver to listen for the change in its state.
      BroadcastReceiver when wifi or 3g network state changed
    • See if volley supports gzip compression. If it does make sure you are compressing the requests. This way you are zipping your request data which can be a substantial improvement in the size. Android Volley: gzip response

Hope this helps.

Upload Image from gallery to server in android

My app is working now. I made following changes to my code.

On activity result part

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
selectedImageUri = null;

switch (requestCode) {
if (resultCode == Activity.RESULT_OK) {
selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);

Bitmap bitmap=BitmapFactory.decodeFile(imagepath);

Toast.makeText(this, selectedImageUri.toString(), Toast.LENGTH_SHORT).show();
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
//use imageUri here to access the image
selectedImageUri = imageUri;
Bitmap bitmap=BitmapFactory.decodeFile(imagepath2);
Toast.makeText(this, selectedImageUri.toString(), Toast.LENGTH_SHORT).show();

} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();

I made two separate functions for launching upload activity.
Function for launching upload activity class for uploading image from gallery to server is this

    private void launchUploadActivity2(boolean isImage){

if (filePath != null) {
// Displaying the image or video on the screen
new UploadImageToServer1().execute();
} else {
"Sorry, file path is missing!", Toast.LENGTH_LONG).show();

Function for uploading activity class for uploading image by capturing to server

    private void launchUploadActivity(boolean isImage){

if (filePath != null) {
// Displaying the image or video on the screen
new UploadImageToServer().execute();
} else {
"Sorry, file path is missing!", Toast.LENGTH_LONG).show();

Upload activity class

private class UploadImageToServer extends AsyncTask<Void, Integer, String> {
protected void onPreExecute() {
// setting progress bar to zero
// progressBar.setProgress(0);

protected String doInBackground(Void... params) {
return uploadFile();

private String uploadFile() {
String responseString = null;

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(AppConfig.URL_PHOTO);

try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {

public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));

File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));

// Extra parameters if you want to pass to server
new StringBody(session.getuid()));

totalSize = entity.getContentLength();

// Making server call

HttpResponse response = httpclient.execute(httppost);

HttpEntity r_entity = response.getEntity();

int statusCode = response.getStatusLine().getStatusCode();

if (statusCode == 200) {
// Server response

responseString = EntityUtils.toString(r_entity);

} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;

} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();

return responseString;


protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);

// showing the server response in an alert dialog




This is the function to create path to a particular folder while capturing image

* Creating file uri to store image/video
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));

* returning image / video
private static File getOutputMediaFile(int type) {

// External sdcard location
File mediaStorageDir = new File(

// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ AppConfig.IMAGE_DIRECTORY_NAME + " directory");
return null;

// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;

return mediaFile;

Now I can upload from both gallery and camera

Upload image into server using retrofit

if someone find it useful, mistake was in 1st parameter "name" here (in my case it should be "file" according to server, instead of "avatar")

MultipartBody.Part body2 = MultipartBody.Part.createFormData("avatar", file.getName(), new FileRequestBody(file, extension));

Response<ResponseBody> response = ApiCaller.getProfileAPI().requestingUploadProfilePhoto("Bearer " + AuthenticationProvider.getInstance().token.token,
if (response.isSuccessful()){
Logger.msg("Photo", ": uploaded successfully " + uri);
Logger.msg("Photo", ": uploaded successfully none" + uri + response.errorBody().string());

So, it was enough to change it and remove all unnecessary stuff.
Also, of course, it is necessary to change service file, according to parameters. I did not pay attention to it enough, because in tutorials it was not mentioned as some important parameter.

How to upload image from gallery to server?

dont hard code the file location, use like this:

String uploadFilePath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/windows/PublicPictures/SamplePictures/";

try to check the file is exist or not like this:

            File file = new File(picturePath);
//write your uploading functionality here.
//file not found please select another file.

in your on activity result method change like this:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };

Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);

int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);

File file = new File(picturePath);
if (file.exists()) {

ImageView imageView = (ImageView) findViewById(R.id.imgView);

and this also:

uploadButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {

dialog = ProgressDialog.show(UploadToServer.this, "",
"Uploading file...", true);

new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("uploading started.....");


Android Upload Image to Server, write path with text fields to a database and retrieve to list view

Finally it worked as required by initialising all aspects in the code.

Android App Upload Image with URL on server

Approach will totally depend upon requirement.

In order to make things faster at some point you will have to add some restrictions.
You will have to think as to what maximum size you will need on server, like 1024, 2048 etc. then you can resize the images being uploaded from client end.

While fetching you can either use some image library at server end to bring resized images at places like thumbnails, or can cache them at user end.

To upload you can either use Multipart or send raw bytes separately in one api , then return server image name and send that in other api which saves rest of the data.

I am not sure of standards but I resize at client end, send Multipart to server or sometimes raw also (depending upon what framework I am using at backend) and fetch un resized images from server and cache them.

Hope this provides some help.


Upload Image to server in android by Httppost

You can upload image to the server using http post multi-part. Here is the link which will help you out.



And one more way to uploading image is, convert it into Base64 and than upload. Check the below link.

Android upload image to server using base64

Related Topics

Leave a reply