My previous tutorial explains how to download a file by showing a progress bar. In this article I am going to explain how to upload a file to server by showing the progress bar. Using this tutorial you can build an app like Instagram where you can capture image or record a video using camera and then upload to a server. On the server side, I used PHP language to read the file and moved it to a particular location.

The best thing about this article is, it works well with larger file uploads too without any out of memory errors. I have tested the app by uploading 50MB file flawlessly.

android file upload with progress bar

Prerequisite

As this article uploads the image/video taken from camera, you need to have knowledge over android camera module. So I recommend you go through my previous tutorial Android Working with Camera which gives you an overview of integrating camera in your android apps.

1. Creating Android Project

1. In Eclipse create a new android project by navigating to File ⇒ New ⇒ Android Application Project and fill out all the required details.

2. Open strings.xml located under res ⇒ values and add below string values.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Camera File Upload</string>
    <string name="btnTakePicture">Capture Image</string>
    <string name="btnRecordVideo">Record Video</string>
    <string name="or">(or)</string>
    <string name="btnUploadToServer">Upload to Server</string>

</resources>

3. Add below color values in colors.xml located under res ⇒ values folder.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <color name="view_background">#e8ecfa</color>
    <color name="btn_bg">#277bec</color>
    <color name="white">#ffffff</color>
    <color name="txt_font">#4e5572</color>
    <color name="action_bar">#1f2649</color>

</resources>

4. Now under src folder create a new class named Config.java. This class file contains file upload URL and image directory name to save the image/video on mobile memory. You will have to replace the file upload url with yours while testing.

package info.androidhive.camerafileupload;

public class Config {
	// File upload url (replace the ip with your server address)
	public static final String FILE_UPLOAD_URL = "http://192.168.0.104/AndroidFileUpload/fileUpload.php";
	
	// Directory name to store captured images and videos
    public static final String IMAGE_DIRECTORY_NAME = "Android File Upload";
}

5. Create a class named AndroidMultiPartEntity.java and paste below code. This class is a custom MultipartEntity class which provides very important functionality required for this project such as progress bar incrementation.

package info.androidhive.camerafileupload;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;

@SuppressWarnings("deprecation")
public class AndroidMultiPartEntity extends MultipartEntity

{

	private final ProgressListener listener;

	public AndroidMultiPartEntity(final ProgressListener listener) {
		super();
		this.listener = listener;
	}

	public AndroidMultiPartEntity(final HttpMultipartMode mode,
			final ProgressListener listener) {
		super(mode);
		this.listener = listener;
	}

	public AndroidMultiPartEntity(HttpMultipartMode mode, final String boundary,
			final Charset charset, final ProgressListener listener) {
		super(mode, boundary, charset);
		this.listener = listener;
	}

	@Override
	public void writeTo(final OutputStream outstream) throws IOException {
		super.writeTo(new CountingOutputStream(outstream, this.listener));
	}

	public static interface ProgressListener {
		void transferred(long num);
	}

	public static class CountingOutputStream extends FilterOutputStream {

		private final ProgressListener listener;
		private long transferred;

		public CountingOutputStream(final OutputStream out,
				final ProgressListener listener) {
			super(out);
			this.listener = listener;
			this.transferred = 0;
		}

		public void write(byte[] b, int off, int len) throws IOException {
			out.write(b, off, len);
			this.transferred += len;
			this.listener.transferred(this.transferred);
		}

		public void write(int b) throws IOException {
			out.write(b);
			this.transferred++;
			this.listener.transferred(this.transferred);
		}
	}
}

Now we’ll add camera support in our app by creating a simple screen with two buttons to invoke camera app to capture image or record video.

6. Open your AndroidManifest.xml file and add required permissions. You can notice that UploadActivity also added in below manifest file. We’ll create it in few minutes.

INTERNET – Required to make network calls
WRITE_EXTERNAL_STORAGE – Required to store image/video on to storage
RECORD_AUDIO – Required to record audio along with video

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.camerafileupload"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="21" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="info.androidhive.camerafileupload.MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="info.androidhive.camerafileupload.UploadActivity"
            android:screenOrientation="portrait" >
        </activity>
    </application>

</manifest>

7. Open the layout file of your main activity (activity_main.xml) and add below code. This creates a layout with two buttons.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/view_background"
    android:baselineAligned="false"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:orientation="vertical" >

        <!-- Capture picture button -->

        <Button
            android:id="@+id/btnCapturePicture"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:background="@color/btn_bg"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:text="@string/btnTakePicture"
            android:textColor="@color/white" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:gravity="center_horizontal"
            android:text="@string/or"
            android:textColor="@color/txt_font" />

        <!-- Record video button -->

        <Button
            android:id="@+id/btnRecordVideo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/btn_bg"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:text="@string/btnRecordVideo"
            android:textColor="@color/white" />
    </LinearLayout>

</RelativeLayout>

8. Add below camera related code in your MainActivity.java class. This code is directly taken from this tutorial.

In brief what this activity will do is,

> Camera app will be launched on tapping take picture or record video button.
> Once the image / video is captured, it will be stored on to mobile SDCard.
> Finally UploadActivity will be launched by passing the SDCard path of the media that is captured. The process of uploading will be done in UploadActivity.

package info.androidhive.camerafileupload;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	// LogCat tag
	private static final String TAG = MainActivity.class.getSimpleName();
	
 
    // Camera activity request codes
    private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
    private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
    
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;
 
    private Uri fileUri; // file url to store image/video
    
    private Button btnCapturePicture, btnRecordVideo;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Changing action bar background color
        // These two lines are not needed
        getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));
 
        btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
        btnRecordVideo = (Button) findViewById(R.id.btnRecordVideo);
 
        /**
         * Capture image button click event
         */
        btnCapturePicture.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                // capture picture
                captureImage();
            }
        });
 
        /**
         * Record video button click event
         */
        btnRecordVideo.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                // record video
                recordVideo();
            }
        });
 
        // Checking camera availability
        if (!isDeviceSupportCamera()) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! Your device doesn't support camera",
                    Toast.LENGTH_LONG).show();
            // will close the app if the device does't have camera
            finish();
        }
    }
 
    /**
     * Checking device has camera hardware or not
     * */
    private boolean isDeviceSupportCamera() {
        if (getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }
 
    /**
     * Launching camera app to capture image
     */
    private void captureImage() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 
        fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
 
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
 
        // start the image capture Intent
        startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
    }
    
    /**
     * Launching camera app to record video
     */
    private void recordVideo() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
 
        fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
 
        // set video quality
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
 
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
                                                            // name
 
        // start the video capture Intent
        startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
    }
 
    /**
     * Here we store the file url as it will be null after returning from camera
     * app
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
 
        // save file url in bundle as it will be null on screen orientation
        // changes
        outState.putParcelable("file_uri", fileUri);
    }
 
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
 
        // get the file url
        fileUri = savedInstanceState.getParcelable("file_uri");
    }
 
    
 
    /**
     * Receiving activity result method will be called after closing the camera
     * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // if the result is capturing Image
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                
            	// successfully captured the image
                // launching upload activity
            	launchUploadActivity(true);
            	
            	
            } else if (resultCode == RESULT_CANCELED) {
                
            	// user cancelled Image capture
                Toast.makeText(getApplicationContext(),
                        "User cancelled image capture", Toast.LENGTH_SHORT)
                        .show();
            
            } else {
                // failed to capture image
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                        .show();
            }
        
        } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                
            	// video successfully recorded
                // launching upload activity
            	launchUploadActivity(false);
            
            } else if (resultCode == RESULT_CANCELED) {
                
            	// user cancelled recording
                Toast.makeText(getApplicationContext(),
                        "User cancelled video recording", Toast.LENGTH_SHORT)
                        .show();
            
            } else {
                // failed to record video
                Toast.makeText(getApplicationContext(),
                        "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }
    
    private void launchUploadActivity(boolean isImage){
    	Intent i = new Intent(MainActivity.this, UploadActivity.class);
        i.putExtra("filePath", fileUri.getPath());
        i.putExtra("isImage", isImage);
        startActivity(i);
    }
     
    /**
     * ------------ Helper Methods ---------------------- 
     * */
 
    /**
     * 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(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                Config.IMAGE_DIRECTORY_NAME);
 
        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(TAG, "Oops! Failed create "
                        + Config.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 if you run the app, you should see following output.

android-file-upload-camera-screen
android-file-upload-camera-taking-camera-picture

Once you are able to launch camera and capture images, we can move forward and start creating the upload activity.

9. Create an xml file under res ⇒ layout folder named activity_upload.xml. This layout contains ImageView, VideoView to preview the captured media and a ProgressBar to show uploading progress.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/view_background"
    android:orientation="vertical"
    android:padding="10dp" >

    

    <!-- To display picture taken -->

    <ImageView
        android:id="@+id/imgPreview"
        android:layout_width="fill_parent"
        android:layout_height="200dp"
        android:visibility="gone" 
        android:layout_marginTop="15dp"/>

    <!-- Videoview to preview recorded video -->

    <VideoView
        android:id="@+id/videoPreview"
        android:layout_width="fill_parent"
        android:layout_height="400dp"
        android:visibility="gone" 
        android:layout_marginTop="15dp"/>

    <TextView
        android:id="@+id/txtPercentage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="15dp"
        android:layout_marginTop="15dp"
        android:textColor="@color/txt_font"
        android:textSize="30dp" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="20dp"
        android:layout_marginBottom="35dp" 
        android:visibility="gone"/>

    <Button
        android:id="@+id/btnUpload"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="@color/btn_bg"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:text="@string/btnUploadToServer"
        android:textColor="@color/white" 
        android:layout_marginBottom="20dp"/>

</LinearLayout>

10. Create a class named UploadActivity.java and paste below code. In this activity

> The path of captured camera image/video is received from MainActivity and image/video is displayed on the screen for preview purpose.
> UploadFileToServer async method takes care of uploading file to server and updating the Progress Bar.

package info.androidhive.camerafileupload;

import info.androidhive.camerafileupload.AndroidMultiPartEntity.ProgressListener;

import java.io.File;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

public class UploadActivity extends Activity {
	// LogCat tag
	private static final String TAG = MainActivity.class.getSimpleName();

	private ProgressBar progressBar;
	private String filePath = null;
	private TextView txtPercentage;
	private ImageView imgPreview;
	private VideoView vidPreview;
	private Button btnUpload;
	long totalSize = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_upload);
		txtPercentage = (TextView) findViewById(R.id.txtPercentage);
		btnUpload = (Button) findViewById(R.id.btnUpload);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		imgPreview = (ImageView) findViewById(R.id.imgPreview);
		vidPreview = (VideoView) findViewById(R.id.videoPreview);

		// Changing action bar background color
		getActionBar().setBackgroundDrawable(
				new ColorDrawable(Color.parseColor(getResources().getString(
						R.color.action_bar))));

		// Receiving the data from previous activity
		Intent i = getIntent();

		// image or video path that is captured in previous activity
		filePath = i.getStringExtra("filePath");

		// boolean flag to identify the media type, image or video
		boolean isImage = i.getBooleanExtra("isImage", true);

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

		btnUpload.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// uploading the file to server
				new UploadFileToServer().execute();
			}
		});

	}

	/**
	 * Displaying captured image/video on the screen
	 * */
	private void previewMedia(boolean isImage) {
		// Checking whether captured media is image or video
		if (isImage) {
			imgPreview.setVisibility(View.VISIBLE);
			vidPreview.setVisibility(View.GONE);
			// bimatp factory
			BitmapFactory.Options options = new BitmapFactory.Options();

			// down sizing image as it throws OutOfMemory Exception for larger
			// images
			options.inSampleSize = 8;

			final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

			imgPreview.setImageBitmap(bitmap);
		} else {
			imgPreview.setVisibility(View.GONE);
			vidPreview.setVisibility(View.VISIBLE);
			vidPreview.setVideoPath(filePath);
			// start playing
			vidPreview.start();
		}
	}

	/**
	 * Uploading the file to server
	 * */
	private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
		@Override
		protected void onPreExecute() {
			// setting progress bar to zero
			progressBar.setProgress(0);
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			// Making progress bar visible
			progressBar.setVisibility(View.VISIBLE);

			// updating progress bar value
			progressBar.setProgress(progress[0]);

			// updating percentage value
			txtPercentage.setText(String.valueOf(progress[0]) + "%");
		}

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

		@SuppressWarnings("deprecation")
		private String uploadFile() {
			String responseString = null;

			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);

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

							@Override
							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
				entity.addPart("website",
						new StringBody("www.androidhive.info"));
				entity.addPart("email", new StringBody("abc@gmail.com"));

				totalSize = entity.getContentLength();
				httppost.setEntity(entity);

				// 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;

		}

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

			// showing the server response in an alert dialog
			showAlert(result);

			super.onPostExecute(result);
		}

	}

	/**
	 * Method to show alert dialog
	 * */
	private void showAlert(String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(message).setTitle("Response from Servers")
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// do nothing
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

}

Until now we are done with android project. Now let’s quickly create the PHP project to receive the file that is being sent from android app. But before that, we need to do small configuration changes to WAMP server.

2. Installing & Configuring WAMP Server

1. Download and install WAMP software. On windows machine, WAMP will be installed at C:\wamp location.

2. Open php.ini and modify below values. By default wamp server allows maximum of 2MB file only to upload. After changing the below values, you can upload the files upto 50MB size.

wamp-server-editing-php.ini-file
upload_max_filesize = 50M
post_max_size = 50M
max_input_time = 300
max_execution_time = 300

3. Now restart the WAMP server.

3. Creating PHP Project

1. Go inside C:\wamp\www and create a folder named AndroidFileUpload. This will be the root directory of our project.

2. Now go into AndroidFileUpload folder and create a folder named uploads to keep all the uploaded files.

3. Create a file named fileUpload.php and paste below content. Below php code takes care of receiving the files from android app and store them in uploads folder. Upon the processing the file, server responds with a JSON message.

<?php

// Path to move uploaded files
$target_path = "uploads/";

// array for final json respone
$response = array();

// getting server ip address
$server_ip = gethostbyname(gethostname());

// final file url that is being uploaded
$file_upload_url = 'http://' . $server_ip . '/' . 'AndroidFileUpload' . '/' . $target_path;


if (isset($_FILES['image']['name'])) {
    $target_path = $target_path . basename($_FILES['image']['name']);

    // reading other post parameters
    $email = isset($_POST['email']) ? $_POST['email'] : '';
    $website = isset($_POST['website']) ? $_POST['website'] : '';

    $response['file_name'] = basename($_FILES['image']['name']);
    $response['email'] = $email;
    $response['website'] = $website;

    try {
        // Throws exception incase file is not being moved
        if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
            // make error flag true
            $response['error'] = true;
            $response['message'] = 'Could not move the file!';
        }

        // File successfully uploaded
        $response['message'] = 'File uploaded successfully!';
        $response['error'] = false;
        $response['file_path'] = $file_upload_url . basename($_FILES['image']['name']);
    } catch (Exception $e) {
        // Exception occurred. Make error flag true
        $response['error'] = true;
        $response['message'] = $e->getMessage();
    }
} else {
    // File parameter is missing
    $response['error'] = true;
    $response['message'] = 'Not received any file!F';
}

// Echo final json response to client
echo json_encode($response);
?>

Below is the sample JSON response if the file is uploaded successfully. You can use error value to verify the upload on android side.

{
    "file_name": "DSC_0021.JPG",
    "email": "admin@androidhive.info",
    "website": "www.androidhive.info",
    "message": "File uploaded successfully!",
    "error": false,
    "file_path": "http://192.168.0.104/AndroidFileUpload/uploads/DSC_0021.JPG"
}

4. Testing the File Upload (localhost)

The following steps shows you how to test the both apps together locally.

1. Connect the both the devices (machine running the wamp server & android mobile) to same wifi network.

2. Start the WAMP server.

3. Get the ip address of the machine that is running the PHP project. You can get the ip address by typing ipconfig in command prompt. (On mac os, use ifconfig to get the ip address)

4. Replace the ip address in Config.java (check 4th step in android project) with your ip address.

5. Deploy & run the android app on the mobile.

android-uploading-camera-picture-to-server
android-uploading-camera-picture-to-server1
android-uploading-camera-picture-to-server2

References
1. Stackoverflow Question about file upload with progress bar.

2. Icon that I used as app icon.

Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Excellent job. Could teach how to send MP3 audio.

    • Everything is same. In UploadActivity just assign the MP3 file path to filePath variable.

      • sreeshty raychoudhury

        thankx for the awesome tutorial,can you help me out where and how can I deploy those rest api to go live.any tutorial will help.

  • mishael95

    Nice one mate

  • waytoweb jain

    hey i want help on this program. i debug application all program is working well. in UploadActivity.java
    // Making server call
    HttpResponse response = httpclient.execute(httppost);
    when debug point come at here. application will stop working.
    nothing happen after this…. please help me. from server side same code put as you develop

    Exception come as org.apache.http.NoHttpResponseException: The target server failed to respond.
    this is error come after 5 to 6 minits. please solve this for me

    • Jackson Pollocks

      the error is clear Target server failed to respond! the host you are connecting to is unreachable

  • dan julian

    Nice tutorial Ravi, what emulator are you using and how do i get it??

    • Its not an emulator. I recorded the video on my mobile and placed it on nexus 5 image while editing the video.

  • waytoweb jain

    thank ravi, its working now. realy thank you

  • Rudi

    thanks ravi, I really like the tutorial you

  • Harish A

    Can you teach something similar for receiving a file back from server. Like how Picture message in whatsapp does.

  • Dung

    Thanks tutorial 😀
    I get error
    eclipse File did not upload: Could not move file

    log error:

    PHP Notice: Undefined index: image in /home/../public_html/AndroidFileUpload/fileUpload.php on line 3
    PHP Notice: Undefined index: image in /home//public_html/AndroidFileUpload/fileUpload.php on line 14
    PHP Notice: Undefined index: image in /home/./public_html/AndroidFileUpload/fileUpload.php on line 18

  • Ahmad

    Good Tutorial Ravi, but what if video file it too large? can i upload it also inside AsyncTask.
    as documented it works ideally just for short operations. what can i use in long operations?

  • Korey

    “MultipartEntity cannot be resolved to a type Error” and “The constructor AndroidMultiPartEntity(new ProgressListener(){}) is undefined” Error cant figure it out

  • waytoweb jain

    hey one more issues are there. its not working in wifi. and easy work on network data. why this happen please help me out

  • Vipul Thawre

    nice sir

  • sangu

    Thanks ravi and how to return the encrypted file name apart from returning the same image name.

  • Muhammad Zubair

    @Ravi
    can this be done by using Volley
    i know you can upload image but i am asking about video 🙂

  • MD Danish Ansari

    This is an awesome app tutorial.

    Can we just do that using local images or videos ? Like choosing from gallery or file explorer.
    That will be cool.

    • You can do it. All we need to set is just send the file path to UploadActivity.

      • MD Danish Ansari

        thanks big bro…:)

      • Guest

        one more little query..
        will my files be uploaded if my pc is closed. and when i turn it on.
        will i be able see those uploaded files..

  • badname

    very cool tutorial Tank you this awsome 😀 . i have a idea for complate your Own instagram or online gallery , make part 2 for this tutorial: recive files from server and show like instagram or grid view gallery 😀

    (Merger or mix this with (volley tutorials, like facebook)

  • badname

    a question : whether this way secure ?
    users cant upload a r57 or c99 shell for hack server ?

    • You have to verify what kind of file user is uploading on the server side.

  • Korey

    what about off the same network…ie from tmobile network to your home PC pretty sure port fwding right?

  • Jaydeep Goyani

    It’s nice work. awesome
    here how to save image url in database ?

  • Jaydeep Goyani

    sir , how to select multiple photo from gallery. and upload to the server.

    • jaydeep

      getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));

      gives error

      • Vineeth KK

        Just remove this line

  • Marcos Campos

    Hi rave great tutorial! waiting for tutorial Chromecast for android !!!

  • Guest

    what changes should i make for uploading audio file from media???

  • Bhagyasri Patel

    I am getting the following error in my phone:

    Response from server: org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.1.102 refused

    when I am accessing the link http://192.168.1.102/AndroidFileUpload/fileUpload.php from browser then it is working fine and i m getting this output:{“error”:true,”message”:”Not received any file!F”}

    I think there is some problem with the connection between android phone and server…please help me with this…

    • Amadeus Prime

      Dear the problem is not in the connection, please follow the below steps which will resolve your problem :

      first: go to Config.java and make sure you enter the appropriate values in the FILE_UPLOAD_URL
      public static final String FILE_UPLOAD_URL = “http://your IP Address:port for your apache server/AndroidFileUpload/fileUpload.php”

      ip address followed by : and your port number that you use in your local host

      second problem in this app which is not mentioned is the httpmime-4.2.6 please go to this link and download the appropriate one and use in your app: http://search.maven.org/#artifactdetails%7Corg.apache.httpcomponents%7Chttpmime%7C4.2.6%7Cjar (third one in the list is called “httpmime-4.2.6.jar”) download it and include it in your app in the libs folder ( to be able to use it after including it in the lib folder: right click on your app name and select properties and then go to Java Build Path and select Add JARs… button on the right menu and then expand your project and select it from the lib folder and then click ok.

      keep the PHP file as it is dont change anything run the app using your phone it must work

      Regards

  • EmileH2000

    Wonderful tutorial Ravi, please could you tell me how I can do this and upload a string as well, because I’m using the rest api you showed us in a precious tutorial of yours, and I need to authenticate all uploads to the api. So my question is “How to upload a string and image/video to server (php) with progress bar?”. Thanks!

  • Ralfh

    Hi. Thanks Ravi. This is a very good tutorial. But, please help me with the error in this imports

    import org.apache.http.entity.mime.HttpMultipartMode;
    import org.apache.http.entity.mime.MultipartEntity;

    • Hi Ralfh, Thanks for notifying me. It seems I forgot to mention this point. You need to add httpclient-4.3.6.jar, httpcore-4.3.3.jar and httpmime-4.3.6.jar to project’s libs folder. But don’t worry, you can find these jars in the downloaded files for this tutorial.

      • ralfh

        I got it now,. Thanks for the response!

  • MD Danish Ansari

    i exported the apk file..

    everything is going alright…

    as soon as i click on “Upload to Server” button, the application stops unfortunately…

    what is the mistake ????

    • Navi

      You may need to make some changes in your gradle flie:

      it should look something like this:

      apply plugin: ‘com.android.application’

      android {

      compileSdkVersion 21

      buildToolsVersion “21.1.2”

      defaultConfig {

      applicationId “com.navi.navdeep.imagegeotagging”

      minSdkVersion 11

      targetSdkVersion 21

      versionCode 1

      versionName “1.0”

      }

      buildTypes {

      release {

      minifyEnabled false

      proguardFiles getDefaultProguardFile(‘proguard-android.txt’), ‘proguard-rules.pro’

      }

      packagingOptions {

      exclude ‘META-INF/DEPENDENCIES’

      exclude ‘META-INF/LICENSE’

      exclude ‘META-INF/LICENSE.txt’

      exclude ‘META-INF/license.txt’

      exclude ‘META-INF/NOTICE’

      exclude ‘META-INF/NOTICE.txt’

      exclude ‘META-INF/notice.txt’

      exclude ‘META-INF/ASL2.0’

      }

      }

      }

      dependencies {

      compile fileTree(dir: ‘libs’, include: [‘*.jar’])

      compile ‘com.android.support:appcompat-v7:22.1.1’

      compile files (‘libs/httpclient-4.3.6.jar’)

      compile files (‘libs/httpcore-4.3.3.jar’)

      compile files (‘libs/httpmime-4.3.6.jar’)

      }

  • Amadeus

    Hi Ravi,

    the image upload is working properly but when i record a video and upload it to server its showing the progress bar and Iam getting a json response from the server but the video is not showing up in the “Android Folder Upload” folder what would be the problem, any suggestions?

    Many thanks for your efforts
    Amadeus

  • Benny

    Hi ravi,

    whenever I try to run my app I get this:

    Information:Gradle tasks [:app:assembleDebug]

    :app:preBuild

    :app:compileDebugNdk UP-TO-DATE

    :app:preDebugBuild

    :app:checkDebugManifest

    :app:preReleaseBuild

    :app:prepareComAndroidSupportAppcompatV72103Library UP-TO-DATE

    :app:prepareComAndroidSupportSupportV42103Library UP-TO-DATE

    :app:prepareComGoogleAndroidGmsPlayServices6587Library UP-TO-DATE

    :app:prepareDebugDependencies

    :app:compileDebugAidl UP-TO-DATE

    :app:compileDebugRenderscript UP-TO-DATE

    :app:generateDebugBuildConfig UP-TO-DATE

    :app:generateDebugAssets UP-TO-DATE

    :app:mergeDebugAssets UP-TO-DATE

    :app:generateDebugResValues UP-TO-DATE

    :app:generateDebugResources UP-TO-DATE

    :app:mergeDebugResources UP-TO-DATE

    :app:processDebugManifest UP-TO-DATE

    :app:processDebugResources UP-TO-DATE

    :app:generateDebugSources UP-TO-DATE

    :app:compileDebugJava

    Note: C:UsersuserDocumentsCamera – Copy (2)appsrcmainjavacombensoftcameraAndroidMultiPartEntity.java uses or overrides a deprecated API.

    Note: Recompile with -Xlint:deprecation for details.

    :app:preDexDebug

    :app:dexDebug

    :app:processDebugJavaRes UP-TO-DATE

    :app:validateDebugSigning

    :app:packageDebug

    Error:duplicate files during packaging of APK C:UsersuserDocumentsCamera – Copy (2)appbuildoutputsapkapp-debug-unaligned.apk

    Path in archive: META-INF/DEPENDENCIES

    Origin 1: C:UsersuserDocumentsCamera – Copy (2)applibshttpcore-4.3.3.jar

    Origin 2: C:UsersuserDocumentsCamera – Copy (2)applibshttpmime-4.3.6.jar

    You can ignore those files in your build.gradle:

    android {

    packagingOptions {

    exclude ‘META-INF/DEPENDENCIES’

    }

    }

    Error:Execution failed for task ‘:app:packageDebug’.

    > Duplicate files copied in APK META-INF/DEPENDENCIES

    File 1: C:UsersuserDocumentsCamera – Copy (2)applibshttpcore-4.3.3.jar

    File 2: C:UsersuserDocumentsCamera – Copy (2)applibshttpcore-4.3.3.jar

    Information:BUILD FAILED

    Information:Total time: 52.536 secs

    Information:2 errors

    Information:0 warnings

    Information:See complete output in console

    • Prathibha Nandini

      is there any solution for this scenario??

  • Ralfh

    Hey Ravi. Thanks again for this. This helps me alot along with your Google Glass Menu tutorial. However, n uploading the image i put ( new UploadFileToServer().execute(); ) if the filePath != NULL and it doesn’t upload nor returning any errors or anything. Please help me with this. Thank you a alot. As I said before I’m working on google glass.

  • Pedro

    Sir, I just want to ask why ym getting this error?

    javax.net.ssl.sslpeerunverifiedexception no peer certificate

    Please help me. Thanks.

  • RK

    Is it good to use MultiPartEntity ?
    As MultiPartEntity is deprecated, so Retrofit seems a good option

  • Kevin Christie

    Hello,
    I loved this tutorial and everything works fine. I’m facing just one issue though; On some devices running Android 4.4.4, when the camera intent is fired and the default camera app opens up, after the uses captures/records an image/video and taps on the done (tick) icon, the camera relaunches and the user is not taken to the preview screen as it is supposed to.

    I am currently stuck on this issue as it works on some devices without any issues, on some devices, this problem occurs sometimes and on some devices (HTC one m8, Moto G v2), it occurs every time the user captures/records an image/video and clicks done (Xperia devices mostly).

    Any advice on this matter would be deeply appreciated.

    Thanks in advance 🙂
    Cheers!

  • Shanni

    Hi, Ravi

    I’m using Android studio and getting the same error as Benny mentioned when I run the app, please help…

    Information:Gradle tasks [:app:assembleDebug]

    :app:preBuild

    :app:compileDebugNdk UP-TO-DATE

    :app:preDebugBuild

    :app:checkDebugManifest

    :app:preReleaseBuild

    :app:prepareComAndroidSupportAppcompatV72103Library UP-TO-DATE

    :app:prepareComAndroidSupportSupportV42103Library UP-TO-DATE

    :app:prepareComGoogleAndroidGmsPlayServices6587Library UP-TO-DATE

    :app:prepareDebugDependencies

    :app:compileDebugAidl UP-TO-DATE

    :app:compileDebugRenderscript UP-TO-DATE

    :app:generateDebugBuildConfig UP-TO-DATE

    :app:generateDebugAssets UP-TO-DATE

    :app:mergeDebugAssets UP-TO-DATE

    :app:generateDebugResValues UP-TO-DATE

    :app:generateDebugResources UP-TO-DATE

    :app:mergeDebugResources UP-TO-DATE

    :app:processDebugManifest UP-TO-DATE

    :app:processDebugResources UP-TO-DATE

    :app:generateDebugSources UP-TO-DATE

    :app:compileDebugJava

    Note: C:UsersuserDocumentsCamera – Copy (2)appsrcmainjavacombensoftcameraAndroidMultiPartEntity.java uses or overrides a deprecated API.

    Note: Recompile with -Xlint:deprecation for details.

    :app:preDexDebug

    :app:dexDebug

    :app:processDebugJavaRes UP-TO-DATE

    :app:validateDebugSigning

    :app:packageDebug

    Error:duplicate files during packaging of APK C:UsersuserDocumentsCamera – Copy (2)appbuildoutputsapkapp-debug-unaligned.apk

    Path in archive: META-INF/DEPENDENCIES

    Origin 1: C:UsersuserDocumentsCamera – Copy (2)applibshttpcore-4.3.3.jar

    Origin 2: C:UsersuserDocumentsCamera – Copy (2)applibshttpmime-4.3.6.jar

    You can ignore those files in your build.gradle:

    android {

    packagingOptions {

    exclude ‘META-INF/DEPENDENCIES’

    }

    }

    Error:Execution failed for task ‘:app:packageDebug’.

    > Duplicate files copied in APK META-INF/DEPENDENCIES

    File 1: C:UsersuserDocumentsCamera – Copy (2)applibshttpcore-4.3.3.jar

    File 2: C:UsersuserDocumentsCamera – Copy (2)applibshttpcore-4.3.3.jar

    Information:BUILD FAILED

    Information:Total time: 52.536 secs

    Information:2 errors

    Information:0 warnings

    Information:See complete output in console

    • Jed Dilag

      Hi sir shanni, at your build.graddle inside adroid {} try to include this code:
      packagingOptions {
      exclude ‘META-INF/DEPENDENCIES’
      exclude ‘META-INF/LICENSE’
      exclude ‘META-INF/LICENSE.txt’
      exclude ‘META-INF/license.txt’
      exclude ‘META-INF/NOTICE’
      exclude ‘META-INF/NOTICE.txt’
      exclude ‘META-INF/notice.txt’
      exclude ‘META-INF/ASL2.0’
      }
      credits to:
      http://stackoverflow.com/questions/22467127/error-duplicate-files-during-packaging-of-apk

      • Shanni

        Dear sir Jed Dilag,

        Thank you very much,
        I tried the code you provided and it solved the problem of the startup running the app

        Please accept my appreciations
        Shanni

  • Cloyd Revira

    Hi Ravi,

    How can I add header token?

  • Cloyd Revira

    Hi Ravi,

    The image upload is working properly but when I add a extra field for Token authentication the response of the server is error 405. How can I add token to header?.

    Here’s my code:
    httppost.setHeader(“Content-Type”, “multipart/form-data”);
    httppost.addHeader(“X-Auth-Token”, token);

    Thanks,
    Cloyd

  • Andrea

    Hi ravi, this is a useful tutorial.
    I tried to use your your guide and past your code exactly but my app crash when I press upload button 🙁
    I tried to run your apk and works! But when I try to import your project in my eclipse appear an error of buildpath so i can’t modify ip address and can’t generate a new apk.

    What’s the problem? I have follow all tutorial exactly!!!
    p.s. I use xampp so I have htdocs instead of www folder

  • Chera Robinson

    Hi! I have a chat app, and I want to add the functionality to send files to my buddy, and my buddy also send me files too. How could I do this? Thanks! My buddy is in another city…

  • mostafa

    hi,
    thank you for your all good tutorials
    what should i use instead of WAMP in Ubuntu? is it LAMP?

  • Thank for you awesome post, find useful Android Video libraries from android-libs.com

  • Tindi_

    Hi. Nice Tutorial. Seems to be working but I cannot see the uploaded images. Where are they going?

  • Sahitya Kumar Suman

    Hey ravi i have a humble request that give me an tutorial to create a json file …… i need to put data from server i know how to acces it and even accessed your json uploaded in every tutorials but i need to build my own json file and upload it to server ……. just in mean time please give me best of tuts to create json file ………I need to create allmost same type of json file as you have created in ListView example http://api.androidhive.info/contacts/

  • Sahitya Kumar Suman

    Any one who know how to create json file can help me ……… please its request to do so

    • Do you want to generate json from a database?

      • Sahitya Kumar Suman

        yes sir …. i am very much thankful if you help me out of it ………. and very much thanx for your precious reply

      • Sahitya Kumar Suman

        I have even read and done your API article and its successful but the thing is it perform all of the operation in the table which is in database …… but from where i will get the json file to access …… which i need to pass it in my String varible in the application you done in the listview json exmple ……..

      • Sahitya Kumar Suman

        Rply me as soon as possible sir

  • Jed Dilag

    Hi sir Ravi, thank you for this tutorial.

    It’s very helpful for starters like me.

    however, i believe there’s somethings wrong with:

    getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));

    it doesn’t work in my emulator
    also, would you please confirm any alternative with this:

    getActionBar().setBackgroundDrawable(
    new ColorDrawable(Color.parseColor(getResources().getString(
    R.color.action_bar))));

    I am using android studio 1.0.1 running in emulator 4.4.2
    thanks and Regards

    • Shanni

      Hi Jed Dilag,

      I have exactly the same problem as you do with this line of code:

      getActionBar().setBackgroundDrawable(
      new ColorDrawable(Color.parseColor(getResources().getString(
      R.color.action_bar))));

      Please help if you have reached any solution for this error

      Accept my regards

    • Rifky Raymond

      you just replace

      android:minSdkVersion=”11″

      on AndroidManifest.xml file

    • Vineeth KK

      Remove this line will solve problem..

  • Ankit

    Hi,

    Format:- .mp4
    Video Upload successfully but can’t play in mozilla browser.
    Any one know what’s wrong?

    Thanks,

  • Samet

    Hi Ravi,

    Is this php code failed?

    Your php code:

    ...

    // Throws exception incase file is not being moved
    if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
    // make error flag true
    $response['error'] = true;
    $response['message'] = 'Could not move the file!';
    }

    // File successfully uploaded
    $response['message'] = 'File uploaded successfully!';
    $response['error'] = false;
    $response['file_path'] = $file_upload_url . basename($_FILES['image']['name']);

    ...

    Because in this code, “$response[‘error’] = false;” will override to “$response[‘error’] = true;” always time…

  • Neji

    Hi Ravi, excellent tutorial. I noticed that the app crashes after the photo or video is taken. Pls what could be the problem?

  • Rege

    Hello Ravi,

    This is my problem… please help me, because this is very important….
    WHAT IS THIS PROBLEM? :S

    Error:Execution failed for task ‘:app:dexDebug’.

    > com.android.ide.common.internal.LoggedErrorException: Failed to run command:

    C:UsersShadowAppDataLocalAndroidsdkbuild-tools21.1.2dx.bat –dex –no-optimize –output C:UsersShadowAndroidStudioProjectsUploadappbuildintermediatesdexdebug –input-list=C:UsersShadowAndroidStudioProjectsUploadappbuildintermediatestmpdexdebuginputList.txt

    Error Code:

    2

    Output:

    UNEXPECTED TOP-LEVEL EXCEPTION:

    com.android.dex.DexException: Multiple dex files define Landroid/support/annotation/AnimRes;

    at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)

    at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554)

    at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535)

    at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)

    at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)

    at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)

    at com.android.dx.command.dexer.Main.runMonoDex(Main.java:303)

    at com.android.dx.command.dexer.Main.run(Main.java:246)

    at com.android.dx.command.dexer.Main.main(Main.java:215)

    at com.android.dx.command.Main.main(Main.java:106)

  • Prem Nath

    Hello ravi,

    Can you tell me how to compress the video file using ffmpeg library can please share some info. i have tried with the http://androidwarzone.blogspot.in/2011/12/ffmpeg4android.html. it was ok but i need to compress large file and i need to handle progress bar and estimate the time. can you please tell me the way.

  • ashe

    Helo Ravi,
    This is another great tutorial from you.
    Can you tell me what the name of emulator you use?

  • Manul

    Hi and thanks for the post. I have some problem, when I try to upload an image the Response from Servers is Error occurred! HttpSatuts Code:403 I have this URL http://192.168.1.109:80/AndroidFileUpload/fileUpload.php

  • Humayoon

    Ravi Tamada plzz help me i want too store file on cloud files thats i store on cloud like(mp3 and text files,images) and i search alot on MobileAsistant-AppEngine but after created prorject then when i right click on my app pacage explorer then google icon not for mobileAsistant App engine but i am confused what i do

  • Rifky Raymond

    thx, it works

  • richard

    very nice tutorial,can u help me how to do this in windows sql server database?

  • Neo

    Hi,

    Very nice tutorial. However, I am facing issues in running this code. First activity is appearing fine. I am able to take the picture. In the second picture, when I click “Upload the Image”, I ma getting an error. The LogCat is showing the following:

    “02-19 13:25:36.884: E/AndroidRuntime(10637): FATAL EXCEPTION: AsyncTask #1
    02-19 13:25:36.884: E/AndroidRuntime(10637): Process: info.androidhive.camerafileupload, PID: 10637
    02-19 13:25:36.884: E/AndroidRuntime(10637): java.lang.RuntimeException: An error occured while executing doInBackground()
    02-19 13:25:36.884: E/AndroidRuntime(10637): at android.os.AsyncTask$3.done(AsyncTask.java:300)
    02-19 13:25:36.884: E/AndroidRuntime(10637): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
    02-19 13:25:36.884: E/AndroidRuntime(10637): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
    02-19 13:25:36.884: E/AndroidRuntime(10637): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    02-19 13:25:36.884: E/AndroidRuntime(10637): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    02-19 13:25:36.884: E/AndroidRuntime(10637): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    02-19 13:25:36.884: E/AndroidRuntime(10637): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    02-19 13:25:36.884: E/AndroidRuntime(10637): at java.lang.Thread.run(Thread.java:841)
    02-19 13:25:36.884: E/AndroidRuntime(10637): Caused by: java.lang.NoClassDefFoundError: info.androidhive.camerafileupload.AndroidMultiPartEntity
    02-19 13:25:36.884: E/AndroidRuntime(10637): at info.androidhive.camerafileupload.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:155)
    02-19 13:25:36.884: E/AndroidRuntime(10637): at info.androidhive.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:144)
    02-19 13:25:36.884: E/AndroidRuntime(10637): at info.androidhive.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:1)
    02-19 13:25:36.884: E/AndroidRuntime(10637): at android.os.AsyncTask$2.call(AsyncTask.java:288)
    02-19 13:25:36.884: E/AndroidRuntime(10637): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    02-19 13:25:36.884: E/AndroidRuntime(10637): … 4 more
    02-19 13:26:13.734: I/Process(10637): Sending signal. PID: 10637 SIG: 9

    Can anyone check ?

    Thanks in Advance.

    • sathya14

      hi,

      Did you got the solution please share with me i am also facing the same issue

    • nayan

      you got any solution for this ?? i am facing same problem bro.. help me out plz

    • aurelien

      Thanks a lot for your blog. Same probleme here too (eclispe ADT)

      (Edit) Solved : Right Click On eclipse project -> Build Path -> Configure Build Path -> Order and Export -> Make sure http*.jar are all selected

  • Mathiazhagan

    I have got response from server as “Error occured! Http Status Code: 500”. My server is hosted on godaddy.com [Windows].

    • Stylesmylez Io

      Im getting the same

      • Check the apache, php logs for errors on godaddy. This might be problem with some apache extensions.

        • nayan

          hey bro i asked you many times .. plzz help me out yr.. i am requesting u plzz

  • sathya14

    hi

    I am facing issues in running this code

    02-19 13:25:36.884: E/AndroidRuntime(10637): FATAL EXCEPTION: AsyncTask #1
    02-19 13:25:36.884: E/AndroidRuntime(10637): Process: info.androidhive.camerafileupload, PID: 10637
    02-19 13:25:36.884: E/AndroidRuntime(10637): java.lang.RuntimeException: An error occured while executing doInBackground()
    02-19 13:25:36.884: E/AndroidRuntime(10637): at android.os.AsyncTask$3.done(AsyncTask.java:300)
    02-19 13:25:36.884: E/AndroidRuntime(10637): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
    02-19 13:25:36.884: E/AndroidRuntime(10637): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
    02-19 13:25:36.884: E/AndroidRuntime(10637):

    How to solve this is issue…what i do wrong

  • saif

    Hi Ravi!
    Im getting this message “Error occured! Http Status Code: 401”
    please help 🙁

  • nayan

    hi,, thanks for the tutorial but whenever i am click on upload.. its stop working please help me out.. what to do in that case?? what will be error?? i changed ip and also did all setting as per tutoril.. anybody help me out plzz ?? its urgent..

  • Evgeny

    i’ve compiled it at android studio, but it crashed when lauching

  • Yago Alonso

    Hi, than u very much fot this tutorial. I only have one problem wich its getting for difccult including trying to debug the app. When i start to record the video, the video records and save, but when the stop button is presed, the app instead of going to uploadactivity goes again to record video screen. What coul it be?

    Thanks,

    • Are you getting any toast message?

      • Yago Alonso

        nothing, after i click on stop on video record, the app try to go to upload screen, but it gets back to the video record. i have chequed the log an console but nothing is display, no error. Only on video record, pictures goes ok.

        • Did you tried running my project directly. If yes, on which device you are testing it on?

          • Yago Alonso

            Yes, under Samsung S3Mini

          • Then no idea dude. make sure that your log is printing. Sometimes it won’t get printed.

          • nayan

            due please help me out…

          • nayan

            hi,, thanks for the tutorial but whenever i am click on upload.. its
            stop working please help me out.. what to do in that case?? what will
            be error?? i changed ip and also did all setting as per tutoril..
            anybody help me out plzz ?? its urgent..

        • aurelien

          Same problem here with video (Samsung galaxy tab7.0)

  • Guest

    nothing, after i click on stop on video record, the app try to go to upload screen, but it gets back to the video record. i have chequed the log an console but nothing is display, no error. Only on video record, pictures goes ok. Thanks!

  • nayan

    hi,, thanks for the tutorial but whenever i am click on upload.. its
    stop working please help me out.. what to do in that case?? what will
    be error?? i changed ip and also did all setting as per tutoril..
    anybody help me out plzz ??

    • Navi

      You may need to make some changes in your gradle flie:

      it should look something like this:

      apply plugin: ‘com.android.application’

      android {

      compileSdkVersion 21

      buildToolsVersion “21.1.2”

      defaultConfig {

      applicationId “com.navi.navdeep.imagegeotagging”

      minSdkVersion 11

      targetSdkVersion 21

      versionCode 1

      versionName “1.0”

      }

      buildTypes {

      release {

      minifyEnabled false

      proguardFiles getDefaultProguardFile(‘proguard-android.txt’), ‘proguard-rules.pro’

      }

      packagingOptions {

      exclude ‘META-INF/DEPENDENCIES’

      exclude ‘META-INF/LICENSE’

      exclude ‘META-INF/LICENSE.txt’

      exclude ‘META-INF/license.txt’

      exclude ‘META-INF/NOTICE’

      exclude ‘META-INF/NOTICE.txt’

      exclude ‘META-INF/notice.txt’

      exclude ‘META-INF/ASL2.0’

      }

      }

      }

      dependencies {

      compile fileTree(dir: ‘libs’, include: [‘*.jar’])

      compile ‘com.android.support:appcompat-v7:22.1.1’

      compile files (‘libs/httpclient-4.3.6.jar’)

      compile files (‘libs/httpcore-4.3.3.jar’)

      compile files (‘libs/httpmime-4.3.6.jar’)

      }

  • nayan

    hi i am facing this problem ….
    will you tell me how to solve this problem ?? anyone got solution for this ??

    02-27 14:25:55.379: E/AndroidRuntime(1202): FATAL EXCEPTION: AsyncTask #1
    02-27 14:25:55.379: E/AndroidRuntime(1202): Process: com.example.admin.camerafileupload, PID: 1202
    02-27 14:25:55.379: E/AndroidRuntime(1202): java.lang.RuntimeException: An error occured while executing doInBackground()
    02-27 14:25:55.379: E/AndroidRuntime(1202): at android.os.AsyncTask$3.done(AsyncTask.java:300)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at java.lang.Thread.run(Thread.java:818)
    02-27 14:25:55.379: E/AndroidRuntime(1202): Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/james/mime4j/field/Field;
    02-27 14:25:55.379: E/AndroidRuntime(1202): at org.apache.http.entity.mime.MultipartEntity.(MultipartEntity.java:85)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at org.apache.http.entity.mime.MultipartEntity.(MultipartEntity.java:100)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at com.example.admin.camerafileupload.AndroidMultiPartEntity.(AndroidMultiPartEntity.java:20)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at com.example.admin.camerafileupload.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:151)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at com.example.admin.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:140)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at com.example.admin.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:118)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at android.os.AsyncTask$2.call(AsyncTask.java:288)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    02-27 14:25:55.379: E/AndroidRuntime(1202): … 4 more
    02-27 14:25:55.379: E/AndroidRuntime(1202): Caused by: java.lang.ClassNotFoundException: Didn’t find class “org.apache.james.mime4j.field.Field” on path: DexPathList[[zip file “/data/app/com.example.admin.camerafileupload-2/base.apk”],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
    02-27 14:25:55.379: E/AndroidRuntime(1202): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
    02-27 14:25:55.379: E/AndroidRuntime(1202): … 12 more
    02-27 14:25:55.379: E/AndroidRuntime(1202): Suppressed: java.lang.ClassNotFoundException: org.apache.james.mime4j.field.Field
    02-27 14:25:55.379: E/AndroidRuntime(1202): at java.lang.Class.classForName(Native Method)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
    02-27 14:25:55.379: E/AndroidRuntime(1202): at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
    02-27 14:25:55.379: E/AndroidRuntime(1202): … 13 more
    02-27 14:25:55.379: E/AndroidRuntime(1202): Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

  • kalai

    this application cannot working

  • Zoonish Zafar

    awsome work 🙂 but video is not uploading , only images are uploading can u help me kindly thnx 🙂

  • Guest

    03-03 10:30:23.625: E/AndroidRuntime(10256): FATAL EXCEPTION: main

    03-03 10:30:23.625: E/AndroidRuntime(10256): java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.camerafileupload/info.androidhive.camerafileupload.MainActivity}: java.lang.NullPointerException

    03-03 10:30:23.625: E/AndroidRuntime(10256): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2249)

    03-03 10:30:23.625: E/AndroidRuntime(10256): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2299)

    03-03 10:30:23.625: E/AndroidRuntime(10256): at android.app.ActivityThread.access$700(ActivityThread.java:154)

    03-03 10:30:23.625: E/AndroidRuntime(10256): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)

    03-03 10:30:23.625: E/AndroidRuntime(10256): at android.os.Handler.dispatchMessage(Handler.java:99)

    03-03 10:30:23.625: E/AndroidRuntime(10256): at android.os.Looper.loop(Looper.java:137)

    03-03 10:30:23.625: E/AndroidRuntime(10256): at android.app.ActivityThread.main(ActivityThread.java:5306)

    03-03 10:30:23.625: E/AndroidRuntime(10256): at java.lang.reflect.Method.invokeNative(Native Method)

    03-03 10:30:23.625: E/AndroidRuntime(10256): at java.lang.reflect.Method.invoke(Method.java:511)

    03-03 10:30:23.625: E/AndroidRuntime(10256): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)

    03-03 10:30:23.625: E/AndroidRuntime(10256): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)

    03-03 10:30:23.625: E/AndroidRuntime(10256): at dalvik.system.NativeStart.main(Native Method)

    03-03 10:30:23.625: E/AndroidRuntime(10256): Caused by: java.lang.NullPointerException

    03-03 10:30:23.625: E/AndroidRuntime(10256): at info.androidhive.camerafileupload.MainActivity.onCreate(MainActivity.java:46)

    03-03 10:30:23.625: E/AndroidRuntime(10256): at android.app.Activity.performCreate(Activity.java:5255)

    03-03 10:30:23.625: E/AndroidRuntime(10256): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)

    03-03 10:30:23.625: E/AndroidRuntime(10256): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2213)

    03-03 10:30:23.625: E/AndroidRuntime(10256): … 11 more

    • kushagra

      what’s the solution of this error ?

  • saif

    great tuto @ravi8x:disqus but i have this problem when i click button upload to server:
    03-04 05:44:28.640: E/MainActivity(1009): Response from server: java.net.SocketException: sendto failed: ECONNRESET (Connection reset by peer)

  • Great Tutorial !!!!!!!

  • Great Tut Sir… Excellent.

  • Can you post some tutorials on How to Upload The Images to Java and .Net Webservices?

  • Peter Muchiri

    hi,

    great tutorial,i get this everytime i run the app

    Error:(174, 23) error: cannot access SingleBody

    class file for org.apache.james.mime4j.message.SingleBody not found

    Error:Execution failed for task ‘:app:compileDebugJava’.

    > Compilation failed; see the compiler error output for details.

    • Naser

      get the file : httpmime-4.3 and it will be okay

      • Peter Muchiri

        {thanks….it worked}

  • Mark

    Hi,
    I’m trying to compress the image or video file, before uploading it to my server, for faster upload process, because when uploading a video or image, it takes a long time.. Can you help me please?

  • Sivaram636

    Great tutorial ,It works fine in my jelly bean device ,,,But throws Null pointer Exception while using Lollipop device…
    Process: im.pura.purav1, PID: 22901
    java.lang.NullPointerException: file
    at android.net.Uri.fromFile(Uri.java:450)
    at im.pura.purav1.Activities.ChatActivity.getOutputMediaFileUri(ChatActivity.java:641)
    at im.pura.purav1.Activities.ChatActivity.captureImage(ChatActivity.java:487)
    at im.pura.purav1.Activities.ChatActivity.access$600(ChatActivity.java:57)

  • Luan

    Error:duplicate files during packaging of APK C:UsersLuanAndroidStudioProjectsCameraPhotoVideoUploadappbuildoutputsapkapp-debug-unaligned.apk

    Error:Execution failed for task ‘:app:packageDebug’.

    > Duplicate files copied in APK META-INF/DEPENDENCIES

    File 1: C:UsersLuanAndroidStudioProjectsCameraPhotoVideoUploadapplibshttpmime-4.3.6.jar

    File 2: C:UsersLuanAndroidStudioProjectsCameraPhotoVideoUploadapplibshttpmime-4.3.6.jar

    • Sivaram636

      add this into build.gradle file ,

      packagingOptions {
      exclude ‘META-INF/DEPENDENCIES’
      }

  • Great tutorial!

  • http://stackoverflow.com/questions/29041651/how-to-parse-a-php-message-with-java-incorrect-http-format-issue

    the picture doesn’t actually exist on my server..

    Here’s the php file saved on my cloud server

    http://68.169.50.115/AndroidFileUpload/fileUpload.php

    the file never actually is saved to my server..

    http://68.169.50.115/AndroidFileUpload/IMG_20150313_164010.jpg

  • http://stackoverflow.com/questions/29041651/how-to-parse-a-php-message-with-java-incorrect-http-format-issueNot Found

    The requested URL /AndroidFileUpload//IMG_20150313_140600.jpg was not found on this server.

    I changed some psp.. to echo this…

    03-13 14:06:17.935: D/OGG(3448): Link: {“error”:false,”message”:”File uploaded successfully!”,”file_path”:”http://68.169.50.115/AndroidFileUpload/IMG_20150313_140600.jpg”}

    But the file is no where to be found..

  • Kevin

    Hi, great information. On Samsung phones my Image and Video intent is not coming back Vertical, Can somebody please give me information on, keeping my intent to stay in vertical form on all phones.. Thanks in advance!

  • Rupesh

    MultipartEntity is not able to resolve. Please tell me how to solve this.

  • Fred Rueda

    Genial me sirvio mucho me gustaria con volley como se haria gracias por ese tutorial

  • naser zahedi

    i have no error and the wamp and android app are correct ,
    and my android device can see the php file via wifi (with browser) , but when i run the app and touch
    upload button just force close happens .

  • Raaz

    How to upload a image using volley library ???

    • Volley is not good for larger files.

      • Is it possible to upload image through volley ? :O

        • Rei Robin

          I’ve found something similar on github but I have no idea how to properly implement it in my project. Some guidelines would be superb! Since I’ll only be uploading small images on to the server.

          https://github.com/com314159/VolleyMultiPartRequest

          • Volley is not good for large payloads, but it can be implemented and its very easy to do that. I implemented it after I saw the post given in the link bellow on stackoverflow .
            http://stackoverflow.com/questions/16797468/how-to-send-a-multipart-form-data-post-in-android-with-volley?
            In MainActivity.java file create a request object and add it to the request queue.. as given bellow..

            MultipartRequest mr=new MultipartRequest( url, fileObj ,
            new Response.Listener() {
            @Override
            public void onResponse(String response) {
            Toast.makeText(MainActivity.this,response.toString(),Toast.LENGTH_LONG).show();
            }
            },new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_LONG).show();
            }
            });
            mr.setTag(TAG);
            Volley.newRequestQueue(this).add(mr);

  • rontiso

    Can I get a C# replica of the fileUpload.php?

  • Jaydeep Goyani

    capture Image To replace Intent of choose from galley
    but it give blank image …

    private void captureImage() {
    Intent intent = new Intent(Intent.ACTION_PICK,
    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
    }

  • Jaydeep Goyani

    How to Implement choose from gallery image…
    plz HelpmE

  • Rashid Abbas

    google map not showing with signed apk plz help me

  • sustecha

    hello it’s really great tutorial but unfortunately I couldn’t get full code, I tried to download it but I got comprised file, I got file which I couldn’t even able to open it …please help

  • sir, i am getting an error after camera upload. It says could not move file. How can i fix it?

  • Aubry Lungu

    This is a nice tutorial, but I have been trying to get the exact file upload path and storing it in my database, I keep getting errors, 1064 errors, how can I solve my issue?

    • Sepaka Hlongwane

      The upload path is defined in your config.java file. Note that you will have to create “uploads” folder on the folder where you stored your “fileUpload.php”.

      You can modify your php file to something like:

      //insert some values into DB then get last insert ID.

      $target_path = $target_path.basename($_FILES[‘image’][‘name’]);

      //rename your file by appending ID to make it unique
      $filename = $lastPID.basename($_FILES[‘image’][‘name’]);;

      try

      {

      //throw exception if can’t move the file

      if (!move_uploaded_file($_FILES[‘image’][‘tmp_name’], $target_path)) {

      throw new Exception(‘Could not move file’);

      }

      echo “The file ” . $filename .

      ” has been uploaded”;

      } catch (Exception $e)

      {

      die(‘File did not upload: ‘ . $e->getMessage());

      }

      $image = “http://localhost/apps/uploads/”.$filename;

      //insert image url to DB

      I hope this helps

      • Aubry Lungu

        Thank You Very much, but how can I implement this as a intentservice?

  • emma w

    I am getting the errors: Unable to resolve symbol HttpMultipartMode and MultipartEntity. Can anyone help??

    • Sepaka Hlongwane

      You need to ensure that you add http jar files to libs. Then click on “clean project”, finally rebuild your project.

  • murali

    not working ,kindly give your phone no. i will call you.

  • suseela

    camera is working but video recording showing error after recording: sorry, this video cannot be played. and it is not working in mobile (after installing apk file) showing error http 403: forbidden while trying to upload image. please give a solution

    • ganesh

      change the path directory : Android File Upload to AndroidFileUpload

  • Azize Petitkorombo

    I GOT SOME errors in this field of uploadactiviti.java
    what is solution please

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

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

  • NICKSLAB

    Very nice Ravi but I have three questions. I’m not new to development however i’m just starting android development and one important thing that I have found on this platform is that DATA SERVICE really critical to a user’s experience. with that being said.
    Is this the most efficient way to do it?
    Is this realistic for data plan users?
    for large amounts of data would you suggest compression or splitting the data into chunks for upload?

  • Ali Bektas

    Hi, ravi , after taking a video or picture, I get an error. –> “unfortunately Camera File Upload has stopped” and my logchat errors:
    04-19 11:55:47.046: E/StatusBarPolicy(1555): ecio: 34
    04-19 11:55:47.046: E/StatusBarPolicy(1555): iconLevel: 4
    04-19 11:55:49.601: E/StatusBarPolicy(1555): ecio: 34
    04-19 11:55:49.601: E/StatusBarPolicy(1555): iconLevel: 4
    04-19 11:55:54.710: E/StatusBarPolicy(1555): ecio: 34
    04-19 11:55:54.710: E/StatusBarPolicy(1555): iconLevel: 3
    04-19 11:56:00.015: E/ClockWidget(7536): clock_bg portrait
    04-19 11:56:00.015: E/ClockWidget(7536): drawDayText
    04-19 11:56:00.015: E/ClockWidget(7536): width= 50
    04-19 11:56:00.015: E/ClockWidget(7536): widthText= 41.0
    04-19 11:56:00.015: E/ClockWidget(7536): center
    04-19 11:56:03.671: E/StatusBarPolicy(1555): ecio: 34
    04-19 11:56:03.671: E/StatusBarPolicy(1555): iconLevel: 4

    pls, This can help a friend who knows please

  • NerdMan

    Kudos to you brother.

  • Is there any reason why this doesn’t work with httpmime 4.4.1?

  • shubham kumar

    I GOT SOME errors in this field of uploadactiviti.java
    what is solution please

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

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

    • Usama Saeed US

      change your class declaration

      from

      public class uploadToServer extends AsyncTask

      to

      public class uploadToServer extends AsyncTask

    • import package_name.AndroidMultiPartEntity.ProgressListener;
      it will clear your error

  • Mangesh Dabre

    sir i want jsp server..

  • Mangesh Dabre

    Sir , i want jsp server..

  • Sandeep Mishra

    How did u mirror your phone screen as seen in your video tutorial?Can you please share that?

  • dave

    Thanks a lot . keep up the good work.. 🙂

  • Mitko Yanakiev

    Thanks man. Great tutorial. You are the best 🙂

  • Hidayah

    i dont have any error but when try to open it say camera upload file has stopped. what should i do

  • J D

    Mr. Tamada Sir,
    Thank you for a very fine post. I use Glassfish w/ RESTFUL (not WAMP).
    Would I have to make modifications to your client side post or can I use it untouched to upload to my Jersey-JAX Glassfish RESTFUL server?

  • AlEe Khokr

    where is the database creation code ????

    • Manny264

      with the set up i dont think any details are sent to a database just a picture being uploaded to a folder on the server

  • kushagra

    Showing error :- Error occurred! Http Status Code: 500 what should i do ?

  • Raza Abid Abbasi

    Getting Error “NoClassDefFondError”

    06-03 14:47:12.228 27671-27946/com.meshsol.fileuploader E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1

    Process: com.meshsol.fileuploader, PID: 27671

    java.lang.RuntimeException: An error occured while executing doInBackground()

    at android.os.AsyncTask$3.done(AsyncTask.java:300)

    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)

    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)

    at java.util.concurrent.FutureTask.run(FutureTask.java:242)

    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

    at java.lang.Thread.run(Thread.java:848)

    Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.ContentType

    at org.apache.http.entity.mime.content.FileBody.(FileBody.java:89)

    at com.meshsol.fileuploader.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:168)

    at com.meshsol.fileuploader.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:145)

    at com.meshsol.fileuploader.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:123)

    at android.os.AsyncTask$2.call(AsyncTask.java:288)

    at java.util.concurrent.FutureTask.run(FutureTask.java:237)

    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

    at java.lang.Thread.run(Thread.java:848)

    • Add the jar file :
      httpclient-4.3.6.jar
      httpcore-4.3.3.jar
      httpmime-4.3.6.jar

      • NaveenReddy

        i already added .jar files still am getting Error “NoClassDefFondError”, Same as above

        • Try rebuilding your project

        • aya zaki

          hello
          i tried this and it’s work go to properities->java build path ->order and export
          then check all libraries that is you use it then clean and build

          • Niyati Sharma

            How to do that in Android studio?

    • aya zaki

      hello
      i tried this and it’s work go to properities->java build path ->order and export
      then check all libraries that is you use it

    • Manny264

      jar file zip: http://www.java2s.com/Code/JarDownload/httpmime/httpmime-4.1.1.jar.zip implement the jars in your project, and maybe try to take off the strict thread policy.

    • mohsen

      hi reza

      {
      httpClient-4.2.5.jar
      httpcore-4.2.4.jar
      httpmime-4.2.5.jar
      }
      add this in the libs folder of your eclipse project

  • tanersenyuz

    How Can I do this with Csharp. Can you help? Thanks…

  • Denis

    How can I do this, but send to my email????

  • Mahesh Lad
  • Mahesh Lad

    Error:(329, 24) error: cannot access AbstractBody
    class file for org.apache.james.mime4j.message.AbstractBody not found

    Can you please help with this..
    Thanks

    • akash shetty

      Did you get your problem solved? If yes then please help me!

  • rio arfani

    I got response error 413 from server..i use IIS server running PHP..any body can help me please

  • Murugan Jai

    i want to know if the possibilities to read the exact data form PDF file

  • Eric Sjöström Jennerstrand

    I want to use this to upload images to a server online. Can anyone help me or point me in the right direction?

    • Manny264

      do you already have an online server i.e. a website?? create a folder on the website and place the php script on it

  • Drooka

    Thanks a lot for this tutorial but, I have this errors and I don’t know why :/
    I think that I added all necessaries jar files to my project.

    Error:(3, 35) error: package org.apache.http.entity.mime does not exist
    Error:(4, 35) error: package org.apache.http.entity.mime does not exist
    Error:(12, 45) error: cannot find symbol class MultipartEntity
    Error:(22, 41) error: cannot find symbol class HttpMultipartMode
    Error:(28, 35) error: cannot find symbol class HttpMultipartMode
    Error:(34, 5) error: method does not override or implement a method from a supertype
    Error:(36, 9) error: cannot find symbol variable super

  • Manny264

    error java.lang.NoClassDefFoundError for AndroidMultiPartEntity…anyone with this similar problem please help…

  • Tarun

    I am using this code and the file uploading progress is shown but request for file uploading goes to server once the progress bar is completed. Means I want the progress bar to be on until it gets uploaded on the server. Service for file uploading is written in Java.

    Thanks.

  • Amod kumar

    i want to store file in tomcat server to make appliaction for audio download….where i have to put audio file in eclipse juno in Dynamic web project

  • PengQin

    Great! Help me a lot!

    • akash shetty

      Can you help me?

  • senthil babu

    i am facing issue on camara, when i try to launch in android emulator it throws error and the app forced to stop..

    Any ideas?

    07-10 15:15:32.215 2396-2396/com.example.ingegno.takevideo E/AndroidRuntime﹕ FATAL EXCEPTION: main

    Process: com.example.ingegno.takevideo, PID: 2396

    java.lang.NullPointerException: file

    at android.net.Uri.fromFile(Uri.java:447)

    at com.example.ingegno.takevideo.MainActivity.getOutputMediaFileUri(MainActivity.java:230)

    at com.example.ingegno.takevideo.MainActivity.recordVideo(MainActivity.java:129)

    at com.example.ingegno.takevideo.MainActivity.access$100(MainActivity.java:30)

    at com.example.ingegno.takevideo.MainActivity$2.onClick(MainActivity.java:81)

    at android.view.View.performClick(View.java:4780)

    at android.view.View$PerformClick.run(View.java:19866)

    at android.os.Handler.handleCallback(Handler.java:739)

    at android.os.Handler.dispatchMessage(Handler.java:95)

    at android.os.Looper.loop(Looper.java:135)

    at android.app.ActivityThread.main(ActivityThread.java:5257)

    at java.lang.reflect.Method.invoke(Native Method)

    at java.lang.reflect.Method.invoke(Method.java:372)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

    —-

  • Darpan

    Wow! The reason I took a moment to stop and leaving this comment because of your attention to detail. Other demos will tell you how to pick an image, but will not tell that you need to create the Uri yourself, as it is a better practice. As well as, sample the image as it may go large, and savedInstanceState() because many will be pulling their hair as why for some images their uri is null. Great work. (Totally justifies your site’s alexa rank)

    • Thanks Darpan for your support.

      • Carol

        Hi Ravi, how about uploading images from gallery? Please help.

        • It is same as this tutorial. Here we are taking the picture and storing it gallery and uploading it to server. In your case you can directly give your gallery image path.

          • Carol

            Please show me how, I’m new to Android. Thanks

  • Jovi Ormillada

    I have completed your package at Android Studio, but it crashes when launching to android device “Unfortunately, Camera File Upload has stopped”.

    I am using XAMPP Server and I remove httpclient-4.3.6 and httpcore-4.3.3 as dependencies because it occurs errors “Duplicate files copied in APK META/Dependencies.
    Hope you can solve it.

    • jimmy

      i’m having this problem too any fixes?

    • ulaş

      me to , can you resolve this problem?

    • Robin

      Comment this line making camera not stopped anymore:

      //getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));

  • Bipin Bharti

    i cann’t download this code?

  • i’m getting below error org.apache.http.conn.Httphostconnectexcption: connection yo http://192.168.239.116 refused

  • Aaronbc

    I have problem with jdk
    Error:Execution failed for task ‘:app:dexDebug’.
    > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process ‘command ‘C:Program FilesJavajdk1.8.0_45binjava.exe” finished with non-zero exit value 2

  • Philipp

    Is the code open source

  • Philipp

    I have one problem, If I import the project in Android Studio an try to run it I became this error:

    Error: duplicate files during packaging of APK C:UsersPhilippAndroidStudioProjectsCameraPhotoVideoUpload2appbuildoutputsapkapp-debug-unaligned.apk
    Path in archive: META-INF/DEPENDENCIES
    Origin 1: C:UsersPhilippAndroidStudioProjectsCameraPhotoVideoUpload2applibshttpclient-4.3.6.jar
    Origin 2: C:UsersPhilippAndroidStudioProjectsCameraPhotoVideoUpload2applibshttpcore-4.3.3.jar
    You can ignore those files in your build.gradle:
    android {
    packagingOptions {
    exclude ‘META-INF/DEPENDENCIES’
    }
    }

    FAILED

    FAILURE: Build failed with an exception.

    * What went wrong:
    Execution failed for task ‘:app:packageDebug’.
    > Duplicate files copied in APK META-INF/DEPENDENCIES
    File 1: C:UsersPhilippAndroidStudioProjectsCameraPhotoVideoUpload2applibshttpclient-4.3.6.jar
    File 2: C:UsersPhilippAndroidStudioProjectsCameraPhotoVideoUpload2applibshttpcore-4.3.3.jar

    * Try:
    Run with –stacktrace option to get the stack trace. Run with –info or –debug option to get more log output.

    BUILD FAILED

    Can you help me ?

    • akshay katheria

      android {
      android {
      packagingOptions {
      exclude ‘META-INF/DEPENDENCIES’
      exclude ‘META-INF/NOTICE’
      exclude ‘META-INF/LICENSE’
      exclude ‘META-INF/LICENSE.txt’
      exclude ‘META-INF/NOTICE.txt’
      }

      use this your code will run it is build.gradle problem

  • Moh’d Khalil

    Hello Ravi,
    Nice tutorial.
    I’m trying to build a storage app like more or less like drop box, can I use the same code to upload documents like .docx and .pdf? I was using my own code I don’t have problems from Java side, but the PHP is not moving the files. I didn’t try your code yet, so I don’t know if it will work or not

    Thanks

    • Snehil

      Hi , Can you tell me how to make it for upload any kind of file ?

  • Lesarck Xperia

    hi ravi , nice tutorial.

    how can i compress the image before save it?

    i am trying to do it these way , but i get null on data.

    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {

    Bitmap photo = (Bitmap) data.getExtras().get(“data”);

    try {

    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    photo.compress(Bitmap.CompressFormat.JPEG, 50, stream);

    } catch (Exception e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

    }

    }

    • Yeah, this is the correct way to do it. If you want compress it even more, compress it using Zip. On the server you can unzip it.

  • August

    hi. i use Android Studio and there’s no color.xml. do I have to create it? if yes, is it relatable with R.color.action_bar in MainActivity.java? because it stated as error and I can see that the file is colorS.xml, while the error is color (no S).

    • Create a file named with colors.xml

      • varun

        plus 1

      • August

        if I want to upload any kind of file, especially pdf, docx, pptx, which part I need to change?

      • Snehil

        I also want to upload any kind of file , how to do so ?

  • Zhao Jimmy

    Hi Ravi,
    I am you funs, I read lots of your tech articles in your blog, and use many of your code sample, it’s good, thankyou.

    for this blog, I am wondering how to do implement this in Volley? do you have any idea on it?

  • diego bernal

    Hi, i have the same problem of Philipp Can you help us ?

    • SoloRoot

      Hi, you should add:

      android {
      packagingOptions {
      exclude ‘META-INF/LICENSE.txt’
      exclude ‘META-INF/NOTICE.txt’
      }
      }

      to your build.gradle file.

      • Farouk Chamsi Bacha

        put this in gradle

        android {

        packagingOptions {

        exclude ‘META-INF/LICENSE’
        exclude ‘META-INF/DEPENDENCIES’
        exclude ‘META-INF/NOTICE’
        }

        }

        • Farouk Chamsi Bacha

          it will solve your problem

  • sarfaraz

    import org.apache.http.entity.mime.HttpMultipartMode;
    import org.apache.http.entity.mime.MultipartEntity;
    lines showing error in java file name multipartentity
    and extends multipartentity also taking as error help out guys

    • Prakhar Chourasia

      download external jar “httpmime-4.3.1.jar”

  • Grumpy

    Does this code also work for up-loading files to any web server or is it just a local server on the same network?

    • SoloRoot

      It’s working for any web server.

      • Phoenix Lord Yach

        Please can you help with an example on any other web server

  • prasad Vdv

    Hi,

    I have done with my upload url
    i have doubt in request method how to print request method

  • niyati sharma

    I want to upload a pdf file…What are the changes that would to required to do so in your code?

    • August

      did you get the answer? because I want to know it too

      • niyati sharma

        no 🙁

  • Nitin Gupta

    Hello Ravi thanks for code

    i am setting entity

    entity.addPart(“image”, new FileBody(sourceFile));

    i have to send some more values to server but i am getting responce bad request
    please guide me how set header ar extra vaues and send to server my code is given below

    i am not using your php file using my own server.

    Thank you..

    entity.addPart(“image”, new FileBody(sourceFile));
    httppost.setHeader(“Content-Type”, “image/jpeg”); //what is content type here
    httppost.setHeader(“Accept”, “application/json”);
    httppost.setHeader( “X-Api-Key”, apiKey );
    httppost.setHeader(“Identifier-TempId”, String.valueOf(System.currentTimeMillis() / 1000)); //send epoch time
    httppost.setHeader(“Identifier-PostedAt”, date_str);

  • kashif

    thanks ravi for this buityfull tutorial ….this is very helpfull for me bt the problem is when i capture the image is run fine bt when i click upload button then it show unfortunetly the “app name” is closed plz help me for this mishappning..

  • Ramu Penta

    Hi Kashit and pk.

    Download “httpcore-4.3-beta1” and add to your project..It wil solve Your Problem.

  • Imtiaz Khan

    Thanks for such a nice and simple example.
    I m trying to send back acknowledgement message from server to app how can i achieve this thanks in advance…:)

  • AB

    How can the same be implemented using MultipartEntityBuilder?

  • erhan harmankaya

    Helllo, Thanks for your tutorial. It save my time. But i want to ask that, Can i compress pictures before uploading. I changed sampleSize but still pictures are too big (e.g 5 mb) also can we set a max time for Video 🙂 Thanks

    • Ronel Gonzales

      u can compress or re-size the image in server side. it ok to upload original photo and keep it like facebook did.

  • Muhammad Hammad Kakli

    if we develop android app to app text messaging server in PHP then what we can do?

  • August

    hi. I want to upload any kind of file, especially pdf, docx, pptx. which part I need to change?

    • Snehil

      hi . I also want to do same .

      Please tell me if you found anything .

      • nurhannan

        me too..search through many tutorials but cant get it. huhu.
        do you find it?

  • akshay katheria

    getting error while executing previewMedia error is file not found exception

  • Soham Dodia

    Getting error: http status 403
    How to solve?

  • Kapil Kapri

    Hi Ravi,

    Thanks for the nice tutorial ,

    Issue No 1:
    But images are saving in two places :

    1) /storage/emulated/0/dcim/camera/image_name.jpg

    and

    2) /storage/emulated/0/dcim/IMAGE_DIRECTORY_NAME/image_name.jpg

    I want image to be placed only in /storage/emulated/0/dcim/IMAGE_DIRECTORY_NAME

    and

    Issue No 2:

    I want only one image in my private folder /storage/emulated/0/dcim/IMAGE_DIRECTORY_NAME for this i am using same name for every image so that the last image will override the previous one

    Below is the code :

    // Create a media file name
    File mediaFile;

    if (type == MEDIA_TYPE_IMAGE) {
    mediaFile = new File(mediaStorageDir.getPath() + File.separator
    + “IMG_” + MYIMAGE + “.jpg”);
    }

    How to solve the issue No 1 …??

  • Chinnmayi

    I downloaded the code and tried to execute the program but the problem is, it captuers the images then it will show unfortunately stopped instead of going to uploadactivity.. Please help me to solve this problem…

  • Farouk Chamsi Bacha

    Hi it work for me but if the image is bigger than 2 mb the app don’t send the file to php any solution

    • Chinnmayi

      Hi…
      iI downloaded this code and tried to run but it is showing unfortunately stopped can u please help me to solve this problem…
      Thanks

  • ANOOP KUMAR

    How can I make this work in API23.

    • Guest

      Add this code in you MainActivity.java

      private static final int REQUEST_EXTERNAL_STORAGE = 1;
      private static String[] PERMISSIONS_STORAGE = {
      Manifest.permission.READ_EXTERNAL_STORAGE,
      Manifest.permission.WRITE_EXTERNAL_STORAGE
      };

      Call verifyStoragePermissions(this); in onCreate method

      Add this method in MainActivity.java

      public static void verifyStoragePermissions(Activity activity) {
      // Check if we have write permission
      int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

      if (permission != PackageManager.PERMISSION_GRANTED) {
      // We don’t have permission so prompt the user
      ActivityCompat.requestPermissions(
      activity,
      PERMISSIONS_STORAGE,
      REQUEST_EXTERNAL_STORAGE
      );
      }
      }

  • JANAGAMA SANDEEP KUMAR

    Hi Ravi ,

    In this project you used php webservice and i want .net webservice to be called.
    Can you please provide me the server side code,which should work with this application.

  • Poornima

    Hi

    I am using eclipse mars and my android sdk version is 23.4. I downloaded this code and tried to run the code but it always shows unfortunately stopped. I was able to capture image image but then it will show unfortunately stopped instead of going to next activity that is image preview with upload button…. Please anyone help me to solve this problem please its urgent please…..

  • Shilpa

    Hai

    I am using api minsdk version 8 and and target sdk version is 23. What should I use instead of getActionBar(). It would be a great help for me. Thanks in advance.

  • Marian Catalin

    I was wondering if there are any possibilities,after i successfully upload the image to the server if i can retrieve them back on a phone from the server,if there are can you send a link to such a tutorial or send me what modifications should i do to this code in order to achieve that.Thank you.

  • Don

    I get an error at this line:
    getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));

    It is expecting a String-value. I modified the color.xml like shown.
    Could someone pls help?

    • Walid

      same here

      • Remove those lines of code as it is no more recommended.

  • ashwini shahasane

    how to send video type and video url from android to phpdatabase

  • thx a lot man, such great tutorial 😀

  • Husain Saify
    • Zem

      atlast someone got and android studio tutorial, this eclipse tutorial doesn’t help a lot

      • You can import eclipse project and Android Studio, It will be converted.

        • Zem

          I know Ravi, been there done that, I also used a lot of your tutorials and I want to thank you. It would be more wonderful if we use Android Studio because most of the people now are adapting it, plus we enjoy the hassle of problems in gradle specially on imports and versioning together 😀

          • This tutorial is written when Android Studio’s initial days. So I didn’t recommended it. I’ll try to modify this into AS.

          • Daniel Nugent

            I ported this tutorial to Android Studio a while back, the only snag was getting the Apache stuff imported in the build.gradle correctly. It’s on GitHub here: https://github.com/dmnugent80/CameraPhotoUpload

          • Thanks Daniel.

  • Dhara Patel

    i need a demo for pick image from gallery and upload to server

  • mayank gupta

    app rashes on pushing the upload image button. Please help anyone.!!!

  • wajii

    import info.androidhive.camerafileupload.AndroidMultiPartEntity.ProgressListener;

    this library i incuded in uploadActivity class isnt working..and also this portion

    try {

    AndroidMultiPartEntity entity = new AndroidMultiPartEntity(

    new ProgressListener() {

    @Override

    public void transferred(long num) {

    publishProgress((int) ((num / (float) totalSize) * 100));

    }

    });

    is fully underlined and not working …please help me with this issue

    • parthiban m

      try to import ProgressListener() to ur activity.

  • Neil Prasad

    I tried registering with email but did not get any emails for verification? Can you let me know how ?

  • parthiban m

    Hi Ravi, The demo was absolutely fine. But I’m facing some typical issues. When I tried this code for One+ phones, the camera is not responding the upload process couldn’t be completed. Can you please help me how I can solve this issue.

  • Samkeet Jain

    Hi ravi,

    I’m trying to upload image to rails server and my server side take json as the below format.

    {

    posts: {

    title:”my title”,

    file_path: “sfhgadddsdjfha”,

    }

    }

    And this tutorial shows to send json as

    {
    “title”:”my title”,
    “file_path”: “http://192.168.0.104/AndroidFileUpload/uploads/DSC_0021.JPG”

    }

    i need to add image under post json object, anyone pls help me out….

  • Houston Austin Muzamhindo

    There is a nullpointer pointer error Ravi when you run this on Android Lollipop 5.0.1. On my tablet it is working perfectly but I decided to load it on my Galaxy S4 and I’m getting the nullpointer at this line:

    public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
    }

    The error says:

    java.lang.NullPointerException: file
    at android.net.Uri.fromFile(Uri.java:448)
    at com.tagconfirm.TagConfirm.activity.MainActivity.getOutputMediaFileUri(MainActivity.java:339)
    at com.tagconfirm.TagConfirm.activity.MainActivity.openGallery(MainActivity.java:233)
    at com.tagconfirm.TagConfirm.activity.MainActivity.access$200(MainActivity.java:46)
    at com.tagconfirm.TagConfirm.activity.MainActivity$2.onClick(MainActivity.java:139)
    at android.view.View.performClick(View.java:5184)
    at android.view.View$PerformClick.run(View.java:20910)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:145)
    at android.app.ActivityThread.main(ActivityThread.java:5942)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)

    Just a quick google and I’m seeing people talk about “Uri with a ContentResolver”, I don’t know what that is though.

    EDIT:

    Realised the error. Android Manifest had put a maxSDKVersion to 18 on the permission to write to storage. You can approve the comment for others to learn from this if it is common.

  • Ramkesh Yadav

    Hello ,its feels great after using this sample for uploading .but i need upgraded version for this sample ( using http url connection).and its urgent ,can you upgrade this sample soon? or help me .thanx

  • Snehil

    Hi Ravi , Thank you for this great tutorial .
    I want to upload any type of file ,and i changed code for it , but only image/video is uploading .

    Please tell me how to make it for all types of files .
    Thanks

  • shubham vashisht

    hello. i am using remote server which needs username and password for letting access to upload images.. how to do that?

  • Abhidip

    Hi, image upload is not physically done though i get response from server that imge uploaded successfully

  • Ali Alqura’an

    Error:Execution failed for task ‘:app:transformResourcesWithMergeJavaResForDebug’.
    > com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/NOTICE
    File1: D:userProgectsCameraPhotoVideoUploadapplibshttpcore-4.3.3.jar
    File2: D:userProgectsCameraPhotoVideoUploadapplibshttpmime-4.3.6.jar
    File3: D:userProgectsCameraPhotoVideoUploadapplibshttpclient-4.3.6.jar

  • Walid Sarkis

    Hey Ravi, the app is working fine until i try to upload the image/video , i get:

    02-15 14:59:10.635 28315-28672/com.example.walid.livecapture E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1

    Process: com.example.walid.livecapture, PID: 28315

    java.lang.RuntimeException: An error occured while executing doInBackground()

    on the line:

    entity.addPart(“image”, new FileBody(sourceFile));

    any help please?

    • Can I get the complete error log?

      • Walid Sarkis

        Hello Ravi, this is the error:

        02-16 21:45:01.260 18062-18883/com.example.walid.livecapture E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1

        Process: com.example.walid.livecapture, PID: 18062

        java.lang.RuntimeException: An error occured while executing doInBackground()

        at android.os.AsyncTask$3.done(AsyncTask.java:300)

        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)

        at java.util.concurrent.FutureTask.setException(FutureTask.java:222)

        at java.util.concurrent.FutureTask.run(FutureTask.java:242)

        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)

        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

        at java.lang.Thread.run(Thread.java:818)

        Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/entity/ContentType;

        at org.apache.http.entity.mime.content.FileBody.(FileBody.java:89)

        at com.example.walid.livecapture.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:163)

        at com.example.walid.livecapture.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:140)

        at com.example.walid.livecapture.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:118)

        at android.os.AsyncTask$2.call(AsyncTask.java:288)

        at java.util.concurrent.FutureTask.run(FutureTask.java:237)

        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)

        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

        at java.lang.Thread.run(Thread.java:818)

        Caused by: java.lang.ClassNotFoundException: Didn’t find class “org.apache.http.entity.ContentType” on path: DexPathList[[zip file “/data/app/com.example.walid.livecapture-1/base.apk”],nativeLibraryDirectories=[/vendor/lib, /system/lib]]

        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)

        at java.lang.ClassLoader.loadClass(ClassLoader.java:511)

        at java.lang.ClassLoader.loadClass(ClassLoader.java:469)

        at org.apache.http.entity.mime.content.FileBody.(FileBody.java:89)

        at com.example.walid.livecapture.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:163)

        at com.example.walid.livecapture.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:140)

        at com.example.walid.livecapture.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:118)

        at android.os.AsyncTask$2.call(AsyncTask.java:288)

        at java.util.concurrent.FutureTask.run(FutureTask.java:237)

        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)

        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

        at java.lang.Thread.run(Thread.java:818)

        Suppressed: java.lang.ClassNotFoundException: org.apache.http.entity.ContentType

        at java.lang.Class.classForName(Native Method)

        at java.lang.BootClassLoader.findClass(ClassLoader.java:781)

        at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)

        at java.lang.ClassLoader.loadClass(ClassLoader.java:504)

        … 11 more

        Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

      • Walid Sarkis

        hello Ravi, i am trying to reply with the error log but the site is denying my reply , where can i send you the log ? via email or something else ?

        • You can post it with the log. I can approve the comment.

          • Walid Sarkis

            02-17 12:36:32.435 30666-32320/com.example.walid.livecapture E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
            Process: com.example.walid.livecapture, PID: 30666
            java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)

            Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/entity/ContentType;
            at org.apache.http.entity.mime.content.FileBody.(FileBody.java:89)
            at com.example.walid.livecapture.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:163)
            at com.example.walid.livecapture.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:140)
            at com.example.walid.livecapture.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:118)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)

            Caused by: java.lang.ClassNotFoundException: Didn’t find class “org.apache.http.entity.ContentType” on path: DexPathList[[zip file “/data/app/com.example.walid.livecapture-2/base.apk”],nativeLibraryDirectories=[/vendor/lib, /system/lib]]

            at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
            at org.apache.http.entity.mime.content.FileBody.(FileBody.java:89)
            at com.example.walid.livecapture.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:163)
            at com.example.walid.livecapture.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:140)

            at com.example.walid.livecapture.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:118)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
            Suppressed: java.lang.ClassNotFoundException: org.apache.http.entity.ContentType

            at java.lang.Class.classForName(Native Method)
            at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
            at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
            … 11 more
            Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

    • Shaon

      Did you complete the project into android studio? if yes, then What is your dependency. please give e secreen shot

  • Perrito

    this code running into the django service?

    • Perrito

      Yess, it’s only change the URL http://…/?format=json

  • Alexiz Hernandez

    Is there any way that I can have files up to 200 or 300 MB upload to the server? My device records in very high quality and 10 seconds was 22MB. I need videos to be as long as 2 minutes. I tried to upload a 1 minute long video and every time it got to 10%, it would start over.

    • Normally uploading such big files takes too much time. You need to do compress the video before uploading to server. If you insist to upload such big files, do these things.

      1. Allow server to receive files greater than 2MB. You can modify apache config to define maximum upload file size.

      2. On the android, as won’t wait to upload 200MB file, move the upload logic a IntentService class to make http call. In this way, upload task moves to background task.

  • jerom

    how can we select a image from absolute path(for example a hardcoded path from external storage) and submit it to a server,

  • Sharon

    Hey Ravi, all work perfect until, i take photo, then i got massage that image dost exist on the folder that i want to save her,
    look this error i got massage:

    Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Pictures/profile_imagephoto.jpg: open failed: ENOENT (No such file or directory)

    What i can do? help me please

  • Shujhal Singh

    this is only for image uploading if i want upload .doc or.pdf file the ?

  • Shujhal Singh

    have any idea how to do this

  • issak

    i got connection to server localhost refused have u any idea why plz my knowledge about local servers is not good but i tried wamp not work and xampp too any help ?

  • Ricky chiu

    I receive JSON response without error. However, i cannot found the file on the server. It is successfully or not?

  • Ahmad Rifa’i

    hai ravi, org.apache.http is deprecated at Android Level Api 23. I’ve trouble when add library httpmime (HttpMultipartMode), httpcore, etc. Can you hel me about this?

  • Burak

    Hi Ravi, I want to upload video to server but ım have a error.
    Log:

    java.lang.RuntimeException: An error occurred while executing doInBackground()

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:309)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:223)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:242)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/entity/ContentType;

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at org.apache.http.entity.mime.content.FileBody.(FileBody.java:89)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at com.burak.ege.anlatokulunu.video.Upload$UploadFileToServer.uploadFile(Upload.java:166)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at com.burak.ege.anlatokulunu.video.Upload$UploadFileToServer.doInBackground(Upload.java:143)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at com.burak.ege.anlatokulunu.video.Upload$UploadFileToServer.doInBackground(Upload.java:121)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:295)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:237)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn’t find class “org.apache.http.entity.ContentType” on path: DexPathList[[zip file “/data/app/com.burak.ege.anlatokulunu-1/base.apk”],nativeLibraryDirectories=[/data/app/com.burak.ege.anlatokulunu-1/lib/arm, /vendor/lib, /system/lib]]

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.lang.ClassLoader.loadClass(ClassLoader.java:511)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.lang.ClassLoader.loadClass(ClassLoader.java:469)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at org.apache.http.entity.mime.content.FileBody.(FileBody.java:89)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at com.burak.ege.anlatokulunu.video.Upload$UploadFileToServer.uploadFile(Upload.java:166)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at com.burak.ege.anlatokulunu.video.Upload$UploadFileToServer.doInBackground(Upload.java:143)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at com.burak.ege.anlatokulunu.video.Upload$UploadFileToServer.doInBackground(Upload.java:121)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:295)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:237)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: Suppressed: java.lang.ClassNotFoundException: org.apache.http.entity.ContentType

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.lang.Class.classForName(Native Method)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.lang.BootClassLoader.findClass(ClassLoader.java:781)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: at java.lang.ClassLoader.loadClass(ClassLoader.java:504)

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: … 11 more

    03-21 23:45:32.894 19010-19552/com.burak.ege.anlatokulunu E/AndroidRuntime: Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available

    03-21 23:45:33.014 19010-19010/com.burak.ege.anlatokulunu I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@c9d84ad time:21450667

    Error is : entity.addPart(“image”, new FileBody(sourceFile)); Please help me .

    • hihihihi

      I’m having the same problem, we are missing a library:

      org.apache.http.entity.Content

      I can’t find it, have you?

  • Raghav Satyadev

    @ravi8x:disqus can you make us an article on Image uploading with volley library using Multipart , by which we can upload big files to like 2-4 MB sizes. if you can then please contact me on

    raghavsatyadev@gmail.com, please reply fast it’s urgent

    • Hi Raghav

      Volley is not recommended for file uploads. That’s why I didn’t mentioned it.

  • Hani

    I want to upload images on server using Django .I am already having Django code for uploading images from browser and it is working fine.now i want upload images from my android app. Can you please tell me the code for it.

    • There is no different between uploading from browser or the app. All you have to do is post the correct payload from android app. This tutorial already covered how to upload to php server. In your case only the endpoint will change.

      • Hani

        Thanks for your reply sir.but what i mean is i am uploading images with Django web service by my pc using command prompt. so now,i want to upload images from android app on button click by using same webservice. so,will this same code will work for it?

        • What is your command prompt code?

          • Hani

            Are you talking about SHA1?

          • Hani

            Are you asking about SHA1?

          • dimmy

            Please sir how can i download the image back to the app

  • wew

    Thx ravi, but how to upload from gallery ?

  • Marvin Collins

    hi i have downloaded the file but it just cant show content

  • Prakhar Tewari

    My app stops responding on using MultiPartEntity. Please provide me the solution

  • DENDULURI CHAITANYA

    Hey hi after i run this code i get a error as stated below

    :[ Error:Execution failed for task ‘:app:transformClassesWithJarMergingForDebug’.
    > com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/http/message/BasicHeaderElementIterator.class ]..

    How to clear this error ?

  • Pritish Joshi

    What about a tutorial with volley to send multipart images and Files with progress bar

  • md. saifuddin Khan

    why this code is not work properly in android studio?
    show this error when run the app.

    Error:Execution failed for task ‘:app:dexDebug’.
    > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process ‘command ‘C:Program FilesJavajdk1.7.0_51binjava.exe” finished with non-zero exit value 2

    plz help me …

    • WBR

      Hello,
      Try deleting the app/build folder and clean your project (under build).
      It should work.

  • Nick

    hey mate! would post a project regarding uploading an image to server with using HttpUrlConnection?

  • Avik Sutar

    How can i upload multiple files using ur code?
    Please Help sir.

  • Zelotejr Goodluck

    thanx for the tutorial….now i want to play video from local server how can i do that, a little help please

  • Frizar

    Thank you so much Ravi ! , its succesfully , but i want to show in timeline , how to do ?

  • Mudit Sen

    As multipart entity is deprecated , can you suggest a method to it using Volley. I can send you my image uploading request and helper code if you want.

  • Siddhesh Chavan

    hey can you help me ???i want to upload the image in my ftp server and the filepath in mssql database…thanx in advance

    • daniel obrzanowski

      I join with the requests

  • Nam

    Thx tutorial, but how to upload list image ?
    give me solution, pls.

  • Ebin Francis

    how to select multiple images and upload to server using SDK v23

  • Oumnia Boualou

    ravi i want to change the path file name by adding an id from a table from my database can u help me please thanks for the tutorial 🙂

  • Harsh Malhotra

    Hi ravi when I am uploading the video it is giving the path in message but on server there is no video get shown neither that path works…

  • daniel obrzanowski

    I did everything as you described but did not work. I want to send the image to an external FTP server. Ies every gets upload and give nothing. No progress bar appears and the image is not sent to. I did it with smaller files but still nothing. Where is the problem?

  • Vigraman

    Hi Ravi, can you update this article with latest design and industry best practice? I love to see it with material design

  • Ahmet Cevahir Çinar

    Hi, Thank for this good tutorial.
    I get an error. Please help me.

    “FATAL EXCEPTION: main
    Process: tr.com.ahmetcevahircinar.fotosend, PID: 2656
    java.lang.NullPointerException: file
    at android.net.Uri.fromFile”

    I add a screenshot.
    http://s33.postimg.org/wdz3o0dfz/Ads_z.jpg

    Wait your reply.
    Thanks.

    • WBR

      Replace
      if (!mediaStorageDir.mkdirs())
      By
      mediaStorageDir.mkdirs();

      It should work.

  • Mohammad Eqbalazar

    Hello , Can you help me how to reduce the image file before saving ?

  • Nawead Anjum

    error occureed! https status code:403

    • WBR

      Where ? in which step ?

      • SoupaTech

        I had the same error. I don’t remember the exact line, but when uploading the image to the server, the progress bar goes to 100% quickly and then a dialog pops up with the error.

        • WBR

          Can i have the exact error ? Maybe it’s related to your server config ?
          Take a look here https://en.wikipedia.org/wiki/HTTP_403
          Quote “…the server can be reached and understood the request, but refuses to take any further action. Status code 403 responses are the result of the web server being configured to deny access, for some reason, to the requested resource by the client.”

      • Justine Villadelrey

        i have the same problem, when i press upload button and it reaches 100% it displays “Error occurred! Http Status 403”

  • Nawead Anjum

    error occured! https status code:403 plz reply me asap my job is danger zone…..

  • houston49

    Hey anyone. I am hosting with DigitalOcean. Ubuntu 14.04 machine PHP5 but the file is not uploading. I have made the folder 777 and added a group/user to not only root for that folder but still nothing.
    Anyone seen this before?

    • WBR

      Have you some logs of the error ?

  • Nawead Anjum

    if i am not connect both device on same network what will happen.But i got a Error occurred! Http Status 403.

  • Abhishek Pachal

    Awesome.The code ran perfectly.Thank you Ravi.

  • Dhanraj Naik

    great tutorial,i uploaded both image and video using retrofit using this reference.Can you plz tell me how to upload with progress dialog using retrofit .Thank you 🙂

  • android

    Great tutorial!
    Is there any way to compress video before uploading to server?

    • WBR

      There are many algorithm to explore to compress video. I’m not an expert but i think that you should take a look to Java Media Framework (or a library for android)

  • Martin Stanimirov

    How can i upload multiple images?

    • WBR

      Possible using android but not covered in this tutorial

  • Ebin Francis

    How can i upload multiple image

    • WBR

      Possible using android but not covered in this tutorial.

  • lyrificaton

    Hi sorry is there any problem with your project? Why is it having error after i try compiling it? Please help

    • WBR

      Hello,
      Which type of problems ?

  • Åmol Çhavhan

    Ravi Tamada This code specifically throws error on 4.4.4 and 4.4.2 devices. plz check

    error :

    Caused by java.lang.VerifyError: org/apache/http/conn/ssl/a

    at org.apache.http.conn.ssl.SSLSocketFactory.(SSLSocketFactory.java)

    at org.apache.http.impl.conn.SchemeRegistryFactory.createDefault(SchemeRegistryFactory.java:52)

    at org.apache.http.impl.client.AbstractHttpClient.createClientConnectionManager(AbstractHttpClient.java:305)

    at org.apache.http.impl.client.AbstractHttpClient.getConnectionManager(AbstractHttpClient.java:465)

    at org.apache.http.impl.client.AbstractHttpClient.createHttpContext(AbstractHttpClient.java:285)

    at org.apache.http.impl.client.AbstractHttpClient.createHttpParams(AbstractHttpClient.java:799)

    at org.apache.http.impl.client.CloseableHttpClient.doExecute(CloseableHttpClient.java:82)

    at org.apache.http.impl.client.CloseableHttpClient.doExecute(CloseableHttpClient.java:106)

    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)

    at com.speakup.app.services.UploadFileToServer.uploadFile(BackGroundUploadService.java:215)

    at com.speakup.app.services.UploadFileToServer.doInBackground(BackGroundUploadService.java:134)

    at com.speakup.app.services.UploadFileToServer.doInBackground(BackGroundUploadService.java:101)

    at android.os.AsyncTask$2.call(AsyncTask.java:288)

    at java.util.concurrent.FutureTask.run(FutureTask.java:237)

    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)

    at java.lang.Thread.run(Thread.java:841)

  • Sanjana Garg

    Hi Ravi,
    I’m trying to compress the image or video file, before uploading it to my server, for faster upload process, because when uploading a video , it takes a long time.. Can you help me please?Its more important to me..

  • android

    Hi Ravi,
    Thanks for the tutorial!
    I am having two issues :
    1. When I choose video from gallery then how to upload it on server?
    2. Is there any way to compress video file before uploading to server?

    • 1. When I choose video from gallery then how to upload it on server?

      In this article, this is already explained. You just have to give the video path of the sdcard

      2. Is there any way to compress video file before uploading to server?

      I haven’t searched much about it. Search for how facebook, whatsapp compressing their videos.

      • android

        Thanks for replying,
        But mine issue is, I select video from gallery and is successfully uploaded on server but After receiving from server am not able to play it! So May it be coz of video format or something?

        • What is the video format you are uploading? Also check the LogCat for any MediaPlayer errors.

  • Hissam Yousaf

    Hello sir,
    Best tutorials for almost everything in android. But before implementing this solution/method in my project should I look for any new libraries because this post is almost 2 years old(December 18, 2014) and some new libraries may have been created with much more flexibility and support. What is your suggestion?

    • That completely depends upon your app. If you are building an app in which uploading is main intent like instagram, you can choose best library. Or you have a scenario where a profile pic is uploaded, you don’t need a library.But make sure you followed this tutorial first just to understand how upload really works.

  • zaki

    How to upload multiple image like olx doing?

  • Vjy Annd

    Hi Ravi,

    I am getting error like this .. Any idea how to fix this ??

    MainActivity.java
    // Changing action bar background color
    // These two lines are not needed
    getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));

    UploadActivity.java

    // Changing action bar background color
    getActionBar().setBackgroundDrawable(
    new ColorDrawable(Color.parseColor(getResources().getString(
    R.color.action_bar))));

    09-20 18:06:37.279 21398-21398/info.androidhive.camerafileupload E/AndroidRuntime: FATAL EXCEPTION: main
    Process: info.androidhive.camerafileupload, PID: 21398
    java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.camerafileupload/info.androidhive.camerafileupload.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setBackgroundDrawable(android.graphics.drawable.Drawable)’ on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setBackgroundDrawable(android.graphics.drawable.Drawable)’ on a null object reference
    at info.androidhive.camerafileupload.MainActivity.onCreate(MainActivity.java:46)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

    Worked After:

  • Ch Khurram

    Error:Execution failed for task ‘:app:transformResourcesWithMergeJavaResForDebug’.
    > com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/LICENSE
    File1: E:OfficeProjectsMySampleApphttpclient-4.3.6httpclient-4.3.6.jar
    File2: E:OfficeProjectsMySampleApphttpmime-4.3.6httpmime-4.3.6.jar
    File3: E:OfficeProjectsMySampleApphttpcore-4.3.3httpcore-4.3.3.jar

    • Farhan Javed

      apply plugin: ‘com.android.application’

      dependencies

      {

      compile ‘com.android.support:appcompat-v7:21.0.3’

      compile ‘com.android.support:support-v4:21.0.3’

      compile files(‘libs/httpclient-4.3.6.jar’)

      compile files(‘libs/httpcore-4.3.3.jar’)

      compile files(‘libs/httpmime-4.3.6.jar’)

      }

      android

      {

      compileSdkVersion 21

      buildToolsVersion “24.0.2”

      defaultConfig

      {

      applicationId “info.androidhive.camerafileupload”

      minSdkVersion 11

      targetSdkVersion 21

      }

      buildTypes

      {

      release

      {

      minifyEnabled false

      proguardFiles getDefaultProguardFile(‘proguard-android.txt’), ‘proguard-rules.txt’

      }

      }

      packagingOptions {

      exclude ‘META-INF/DEPENDENCIES’

      exclude ‘META-INF/NOTICE’

      exclude ‘META-INF/LICENSE’

      exclude ‘META-INF/NOTICE.txt’

      exclude ‘META-INF/LICENSE.txt’

      }

      }

    • Ch Khurram

      it works okay by adding exclude etc etc … but when i create signed apk . it shown error

  • http://stackoverflow.com/questions/39364469/retrofit2-how-to-upload-image-using-retrofit-in-multipart

    I’m not able to upload my image on server. Always its asking for Image, other data is going but image not. any help?

  • Pawan Kumar

    great tutorial like always

  • Pratik Kotak

    i successfully created the app but whenever i upload anytg i get a error message from server i.e error 404

    • The url you trying to access is incorrect or not accessible from the app.

      • Pratik Kotak

        what can be the solution for that.??

        • What is the url you are using to upload?

          • Pratik Kotak

            hey it worked hosted on my website. Thanks..:)

  • Thank you for providing us so many awesome articles..

    One Request : Can u please make a tutorial on image processing type of stuffs. I mean a basic video or photo editor tutorial 🙁 I am not getting any good tutorial for those type of things..

  • sam

    when i try your code i accrued error this line code
    entity.addPart(“image”, new FileBody(sourceFile));

    java.lang.RuntimeException: An error occurred while executing doInBackground()

    Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/Consts;

    at org.apache.http.entity.mime.content.StringBody.(StringBody.java:148)

    How to solve it?

    • Wouter

      got the same problem, did you fix it already?

  • Matheus Leite

    Hi @ravi8x:disqus , I get the following error:

    java.io.FileNotFoundException: /storage/emulated/0/Pictures/Ajunta photos/IMG_20161014_150335.jpg: open failed: ENOENT (No such file or directory)

    Could you help me?

  • Anne H

    @ravi8x:disqus
    hi ravi i need an example to upload video from gallery to server using base64

  • yadunath narayanan

    Httpclient and httppost are deprecated right,so is it a good practice to use them now?

  • Uyi Oriaghan

    Thank you very much. you saved me with this, its working perfectly. In my app i have another option that selects photo from gallery and it works just as fine but i want to also save that photo it selects from the gallery in the same directory please can you help me with that. thanks

      • Uyi Oriaghan

        Thanks very much i really appreciate this, but i have got one serious issue now because of what i wanna do with the picture, i need the pic to be square. is there a way or some library i can use to present to the user chance of cropping out a square out of the picture. Thanks

      • Uyi Oriaghan

        thanks so much, i have found an effective library to handle it. thanks

      • Abdul Saboor

        But the tutorial you share here is only uploading image from Gallery , i am unable to send any information with image in that tutorial which takes image from gallery and then sent it to the server

  • Uyi Oriaghan

    Hello Guys please i need help with perfecting this upload. It works very fine but anytime my internet connection goes out while uploading the activity crashes. Please help, very very urgent. my email is oriaghan3@gmail.com

    • Uyi Oriaghan

      will it be possible for it to pause and resume when the network arrives as long as the activity is still open

  • evgeny ostrovsky

    can someone guide me how to code the server in django ? a part at least that can handle file upload
    thanks !!!

  • Abdul Saboor

    HOw r u? its awesome tutorial.. I can upload image with ease but i am facing problem in uploading video, response from server always be come error “true” while i sent the video to the server., please help me

  • Abdul Saboor

    When i uploaded video it always said the error “True” message “Not Received any fiile”
    on the other hand i uploaded image successfully . please guide me

  • mousa mohamed

    when im upload video – i have error
    response from servers error occurred http status code : 500

    • Enable php error reporting to see the errors.

  • Lou Sizzo

    I have a problem, at the moment of wanting to upload an image, automatically closes the activity, already made many debugs and I conclude that it is the class AndroidMultiPartEntity that is giving that failure, someone else happened that?

    • in mainactivity:

      //Capture image button click event
      btnCapturePicture.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
      if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
      if(!checkAndRequestPermissions()){
      new AlertDialog.Builder(MainActivity.this)
      .setTitle(“Atención”)
      .setMessage(Html.fromHtml(“La aplicación “+getString(R.string.app_name)+” utiliza los siguientes permisos para funcionar:&nbsp• Camara: Permite fotografiar y grabar videos.&nbsp• Almacenamiento: Permite poder acceder a estas fotografías y videos capturados.Asegúrese de permitir ambos permisos.”))
      .setIcon(R.drawable.ic_launcher)
      .setPositiveButton(“Aceptar”, new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
      habilitarPermisos();
      }
      })
      .show();
      }else{
      captureImage(); // tomar foto
      }
      }else
      captureImage(); // tomar foto
      }
      });

      //Record video button click event
      btnRecordVideo.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
      if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      if(!checkAndRequestPermissions()){
      new AlertDialog.Builder(MainActivity.this)
      .setTitle(“Atención”)
      .setMessage(Html.fromHtml(“La aplicación “+getString(R.string.app_name)+” utiliza los siguientes permisos para funcionar:&nbsp• Camara: Permite fotografiar y grabar videos.&nbsp• Almacenamiento: Permite poder acceder a estas fotografías y videos capturados.Asegúrese de permitir ambos permisos.”))
      .setIcon(R.drawable.ic_launcher)
      .setPositiveButton(“Aceptar”, new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
      habilitarPermisos();
      }
      })
      .show();
      }else{
      recordVideo(); // Grabar video
      }
      }else
      recordVideo(); // Grabar video
      }
      });

      • //checkAndRequestPermissions
        private boolean checkAndRequestPermissions() {
        return ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
        && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        }

        //onRequestPermissionsResult
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        Map perms = new HashMap();
        perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
        perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);

        // Fill with actual results from user
        if (grantResults.length > 0) {
        for (int i = 0; i < permissions.length; i++)
        perms.put(permissions[i], grantResults[i]);
        // Check for both permissions
        if (perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
        && perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        Log.d(TAG, "Todos los Permisos Aceptados");
        //avanzarActividad(isImage);
        } else {
        Log.d(TAG, "Faltan Permisos");
        if(perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
        Toast.makeText(this, "No se podrá usar la camara", Toast.LENGTH_SHORT).show();
        if(perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
        Toast.makeText(this, "No se podrá obtener la fotografía y video", Toast.LENGTH_SHORT).show();
        //avanzarActividad(isImage);
        }
        }
        }

        //habilitarPermisos
        public void habilitarPermisos(){
        final String[] permissions = new String[]{
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE};

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, permissions, SOLICITUD_PERMISO_CAMARA);
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, permissions, SOLICITUD_PERMISO_ALMACENAMIENTO);
        }
        }

  • king

    how to use in volley?

    • in android studio add this en your build.gradle
      compile ‘com.mcxiaoke.volley:library:1.0.18’
      compile “org.apache.httpcomponents:httpmime:4.2.3”

  • Malik Haris

    how can i upload an image in android app? in proper way i mean only app owner can upload a pic

    • Open php.ini and modify below values. By default wamp server allows maximum of 2MB file only to upload. After changing the below values, you can upload the files upto 50MB size.

      upload_max_filesize = 50M
      post_max_size = 50M
      max_input_time = 300
      max_execution_time = 300

  • sadsda

    This is trash… MultipartEntity dead already.

  • Subhanjan

    working fine after making some changes… import these two jar files in library: httpmime-4.3.jar , httpcore-4.3-beta1.jar I need another thing image upload. how to implement that with a text box to rename the image

    • only one: compile “org.apache.httpcomponents:httpmime:4.2.3”

      • Subhanjan

        can you tell me how to implement upload image with some text parameter with this progress bar, I dont want take video option

        • Text as the number of kb or mb? or text as file name?

          • Subhanjan

            text means, I will implement 2 boxes for image upload, where user will input some text about the image, it will be posted to server to a php file where the php file will get it using GET/Post parameter.

      • Vishal Vekariya

        Thanx bro it’s work

  • Rogerio Guimaraes

    Hi Ravi, congratulations for the post. How do I send more than one photo?

  • Dushant Reddy

    Hi Ravi…thanks for your post..its working for me.

  • Sourav Roy

    File did not upload: Could not move file

    • May be folder permissions issue.

      • Sourav Roy

        Yes I needed server write permission. Thank you very much sir.

        • You are welcome:)

          • taimoor shaukat

            this code is not working on android 7 version can you update this tutorial to android 7

  • Sunil Kumar

    Dear sir i want to upload only 1 mb file. Please help me..

  • Sunil Kumar

    I want it in android..

  • Harikrishnan

    Dear Sir,
    I am facing with a FATALExCEPTION,what to do,please help sir
    E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.harikrishnan.cyc10, PID: 30683
    java.lang.NullPointerException: file
    at android.net.Uri.fromFile(Uri.java:452)
    at com.example.harikrishnan.cyc10.MainActivity.getOutputMediaFileUri(MainActivity.java:121)
    at com.example.harikrishnan.cyc10.MainActivity.captureImage(MainActivity.java:50)
    at com.example.harikrishnan.cyc10.MainActivity$1.onClick(MainActivity.java:43)
    at android.view.View.performClick(View.java:5207)
    at android.view.View$PerformClick.run(View.java:21168)
    at android.os.Handler.handleCallback(Handler.java:746)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5443)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

    • Sandhya Bairi

      I am also getting the same error. Did you find any solution?

    • Komal

      I also getting the same error…. is anybody found the solution??

      • Ashna Patel

        Write below lines in your app level gradle file it will solve your error

        android {
        packagingOptions {
        exclude ‘META-INF/DEPENDENCIES.txt’
        exclude ‘META-INF/LICENSE.txt’
        exclude ‘META-INF/NOTICE.txt’
        exclude ‘META-INF/NOTICE’
        exclude ‘META-INF/LICENSE’
        exclude ‘META-INF/DEPENDENCIES’
        exclude ‘META-INF/notice.txt’
        exclude ‘META-INF/license.txt’
        exclude ‘META-INF/dependencies.txt’
        exclude ‘META-INF/LGPL2.1’
        }
        }

  • Ardha Chandra

    Dear Ravi

    This tutorial is the best tutorial as far as I know about uploading files by display a progress bar.

    I faced a problem when I create a class named AndroidMultiPartEntity.java and there is an error that says there are no MultipartEntity extends.

    What is the solution of my problem? Do I have to import the library to get MultipartEntity? If yes, how to import the library of MultipartEntity?

    I am waiting for your guidance and I am very grateful for your help. GOOD JOB 🙂

    Regards,

    Ardha

  • Khalid Qurashi

    hello sir, thanks for the information , i need in converting my android screens into pdf by storing the data presnt in forms, please help me to do it sir

  • I have been following your tutorials since long time. I liked the tutorial and have implemented many times as well. I wanted to know that How to upload multiple images to server using this same technique? This is very important sometimes. Please do reply. Thank you.

  • Fabio

    Exception: IOException: java.io.UnsupportedEncodingException: ISO-8859, Help me !!!

  • anggih setiawan

    please help me,
    error ‘IMG_20170207_014119.jpgFile did not upload: Could not move file’

    <?php
    echo $_FILES['image']['name'] . '’;

    //ini_set(‘upload_max_filesize’, ’10M’);
    //ini_set(‘post_max_size’, ’10M’);
    //ini_set(‘max_input_time’, 300);
    //ini_set(‘max_execution_time’, 300);

    $target_path = “http://192.168.107.71/AndroidFileUpload/uploads/”;
    $target_path = $target_path . basename($_FILES[‘image’][‘name’]);
    try {
    //throw exception if can’t move the file
    if (!move_uploaded_file($_FILES[‘image’][‘tmp_name’], $target_path)) {
    throw new Exception(‘Could not move file’);
    }
    echo “The file ” . basename($_FILES[‘image’][‘name’]) .
    ” has been uploaded”;
    }
    catch (Exception $e) {
    die(‘File did not upload: ‘ . $e->getMessage());
    }
    ?>

  • SAURABH GAUR

    app is working but photos could not upload on server

  • ravindra

    how i can reduce the size of image while taking from external card ,to upload into server
    now images uploading into server but, taking too much time so, could u help me how to compress that images.in android

  • crystal

    when i am trying to bulid it is showing me this error im a new to android studio
    need help

    Error:Execution failed for task ‘:app:transformClassesWithDexForDebug’.
    > com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define Lorg/apache/http/entity/mime/AbstractMultipartForm;

  • Eng-Amal Al Kronz

    Hi, thanks for this tutorial Ravi,,
    I do as you explain and having success upload file but really when I want to display the video from link it’s not found in server and didn’t upload well

  • VICKY ZARE

    Hello Ravi
    can you please convert the backend code in c# language or please suggest me other solution for that

    • Ken Choong

      Why just use Php?

  • chadav

    Hello Ravi
    What all changes should I make to upload image to server from gallery

    • Hi Chadav

      Currently I am image / video is already uploading from Gallery only. You have to skip the camera part and upload the file directly from the gallery.

      • chadav

        I need to upload both from camera and Image galery. I edited your code for that
        This is the server response I got when I try to upload from image galery
        Response from server: java.io.FileNotFoundException: /external/images/media/123 (No such file or directory)

        But there is no problem on uploading from camera.

      • chadav

        I need to upload from both camera and Image gallery.I used your code and edited it. I can succesfully upload image to server via camera.But when I try to upload using gallery this is the response I got from server
        Response from server: java.io.FileNotFoundException: /external/images/media/123 (No such file or directory)

  • Epuser

    Hello Ravi
    How can i crop captured image and get image from galery ?

  • Trupen Meruliya

    Hello brother..

    I want to compress (reduce size) of uploaded video or photo can you help me ..

  • Rushi Pawar

    Bro I am Getting Error when Click on Upload to server Button

    FATAL EXCEPTION: AsyncTask #1
    Process: com.rushi.loginapp, PID: 9391
    java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:304)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)
    Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/entity/ContentType;
    at org.apache.http.entity.mime.content.FileBody.(FileBody.java:89)
    at com.rushi.loginapp.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:175)
    at com.rushi.loginapp.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:152)
    at com.rushi.loginapp.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:130)
    at android.os.AsyncTask$2.call(AsyncTask.java:292)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)
    Caused by: java.lang.ClassNotFoundException: Didn’t find class “org.apache.http.entity.ContentType” on path: DexPathList[[zip file “/data/app/com.rushi.loginapp-1/base.apk”, zip file “/data/app/com.rushi.loginapp-1/split_lib_dependencies_apk.apk”, zip file “/data/app/com.rushi.loginapp-1/split_lib_slice_0_apk.apk”, zip file “/data/app/com.rushi.loginapp-1/split_lib_slice_1_apk.apk”, zip file “/data/app/com.rushi.loginapp-1/split_lib_slice_2_apk.apk”, zip file “/data/app/com.rushi.loginapp-1/split_lib_slice_3_apk.apk”, zip file “/data/app/com.rushi.loginapp-1/split_lib_slice_4_apk.apk”, zip file “/data/app/com.rushi.loginapp-1/split_lib_slice_5_apk.apk”, zip file “/data/app/com.rushi.loginapp-1/split_lib_slice_6_apk.apk”, zip file “/data/app/com.rushi.loginapp-1/split_lib_slice_7_apk.apk”, zip file “/data/app/com.rushi.loginapp-1/split_lib_slice_8_apk.apk”, zip file “/data/app/com.rushi.loginapp-1/split_lib_slice_9_apk.apk”],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
    at org.apache.http.entity.mime.content.FileBody.(FileBody.java:89)
    at com.rushi.loginapp.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:175)
    at com.rushi.loginapp.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:152)
    at com.rushi.loginapp.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:130)
    at android.os.AsyncTask$2.call(AsyncTask.java:292)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)
    Suppressed: java.lang.ClassNotFoundException: org.apache.http.entity.ContentType
    at java.lang.Class.classForName(Native Method)
    at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
    at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
    … 11 more
    Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

    • Fahad Shamsudheen

      hey bro do u solve this error.same errors will be come here can you help me to how to solve this error

      • Neeraj Mehta

        m aslo getting same error .. if u solved it pease tell

    • Fahad Shamsudheen

      Sir this same error will be coming here please help me sir

    • Komal

      Do you found the solution for above?

  • Rishab Kesarwani

    Here is my question…
    I need to upload the video on the Google drive …
    Please help me out to do so…

  • dinh van Chinh

    use AsyncTask inner class has leak memory?

  • muhamad aminruddin

    Why i can’t upload to my linux server.

  • Neeraja

    How can we auto capture images without user interaction? Please help.

  • Ahsan Idrees

    Excelent Work

  • Priyanka

    When i try to run it in my android device, I am getting org.apache.http.conn.HttpHostConnectException:Connection to http://198.16x.x.x refused
    This error is bothering me since last week.
    Have tried all possible solutions.
    Can anyone help me out.

    • taha rafi

      Writing ip only is not enough.You have to write apache port number also like 192.168.x.x:82..

  • Kuldeep Inheritx

    Hi Ravi.
    This is working charm. I want to know that how to cancel HttpRequest if I want to cancel uploading. Your help would be appreciated.

    • Aankur Datta

      try this
      //global declaration or class declaration
      UploadFileToServer serverReq;

      serverReq= new UploadFileToServer();
      serverReq.execute();

      and inside onclick listener for ur cancel button……
      serverReq.cancel(true);

      inside onProgressUpdate….
      if (isCancelled()) break;

  • Aankur Datta

    Pictures no issue, but when am uploading video on a godaddy Linux server, am getting a success response but the file is not getting uploaded. any specific reasons?

    • Aankur Datta

      RE: i think its the file size issue and php move_uploaded_file() doesn’t go to catch. when am uploading a one sec video its working.

      • Ellah Jereza

        same issue here. Have you solved you problem?

        • Aankur Datta

          Na its a shared server issue, works fine on AWS though, let me know if you get a solution

    • Kartikey Bhardwaj

      on GoDaddy, goto PHP Selector (Switch to PHP Options) under Select php version in cPanel.
      upload_max_filesize = ?
      post_max_size = ?
      max_input_time = ?
      max_execution_time = ?
      change these according to your needs.

  • Sathwik Gangisetty

    I’m getting error in UploadActivity.java file the first @override method OnCreate shows error that it can’t override. I’m new to android development, can anyone help me?

  • Robby Ramadhan

    i getting code
    E/MainActivity: Response from server: null
    in android logcat upload sucessfully but file image there is no on folder uploads
    help me

    • Robby Ramadhan

      sorry Response server: its ok but not file image in upload folder..

  • Fahad Shamsudheen

    Sir,
    When i try to run it in my android device,i can’t uploading the capturing image.When i click upload button this errors will be coming….
    FATAL EXCEPTION: AsyncTask #1
    Process: com.example.admin_i3.code, PID: 12065
    java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:304)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)
    Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/entity/ContentType;
    at org.apache.http.entity.mime.content.FileBody.(FileBody.java:89)
    at com.example.admin_i3.code.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:165)
    at com.example.admin_i3.code.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:142)
    at com.example.admin_i3.code.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:120)
    at android.os.AsyncTask$2.call(AsyncTask.java:292)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)
    Caused by: java.lang.ClassNotFoundException: Didn’t find class “org.apache.http.entity.ContentType” on path: DexPathList[[zip file “/data/app/com.example.admin_i3.code-1/base.apk”],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
    at org.apache.http.entity.mime.content.FileBody.(FileBody.java:89)
    at com.example.admin_i3.code.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:165)
    at com.example.admin_i3.code.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:142)
    at com.example.admin_i3.code.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:120)
    at android.os.AsyncTask$2.call(AsyncTask.java:292)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)
    Suppressed: java.lang.ClassNotFoundException: org.apache.http.entity.ContentType
    at java.lang.Class.classForName(Native Method)
    at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
    at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
    … 11 more
    Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

    can u help me to solve this error

  • Ken Choong

    Ravi,I have a simple question,your code is working fine,but I face a little problem,cause sometime,only half of the image being upload to server,which is something like image below,so it load at android with glide also appear like this.Can u give me a little bit advice to prevent this?Or can u let me know why can this happen?
    https://uploads.disquscdn.com/images/ce9a5170a517a371ee4ce1862995e5149937bd45b88c884041d4cc1109af8354.png

  • taimoor shaukat

    can you update this tutorial for android N because in android 7 this code is not working thanks

  • Fahad Shamsudheen

    Anybody is know how to solve this error pls help am still stuck,the error is given below

    FATAL EXCEPTION: AsyncTask #1
    Process: com.example.admin_i3.code, PID: 12065
    java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:304)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
    at java.util.concurrent.Future…(FutureTask.java:242)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)
    Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/entity/ContentType;
    at org.apache.http.entity.mime.content.FileBody.(FileBody.java:89)
    at com.example.admin_i3.code.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:165)
    at com.example.admin_i3.code.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:142)
    at com.example.admin_i3.code.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:120)
    at android.os.AsyncTask$2.call(AsyncTask.java:292)
    at java.util.concurrent.Future…(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)
    Caused by: java.lang.ClassNotFoundException: Didn’t find class “org.apache.http.entity.ContentType” on path: DexPathList[[zip file “/data/app/com.example.admin_i3.code-1/base.apk”],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
    at org.apache.http.entity.mime.content.FileBody.(FileBody.java:89)
    at com.example.admin_i3.code.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:165)
    at com.example.admin_i3.code.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:142)
    at com.example.admin_i3.code.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:120)
    at android.os.AsyncTask$2.call(AsyncTask.java:292)
    at java.util.concurrent.Future…(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)
    Suppressed: java.lang.ClassNotFoundException: org.apache.http.entity.ContentType
    at java.lang.Class.classForName(Native Method)
    at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
    at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
    … 11 more
    Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

  • Yayan Agustyan

    Hi Ravi,
    your code is working fine.
    but I have a problems with image size on result.
    I’m using Samsung J5 to test this code, I always get image with size 3MB up to 4MB.
    can I capture image under 1MB ?

    I need your answer please.
    thanks before.

  • vishesh shah

    Please update your code by not using deprecated classes. We want to use latest classes to upload file with progress.

    • Vikram B

      Use android Volley API

  • Anton Doank

    ravi, can we compress the image before upload it?please add the tutorial to compress the image. you are my master of android…

  • Puneet Kaur

    How to determine what method to use for decoding the image string?
    Can I get the PHP code to upload image from this string?

    I’m getting this type of string “–apiclient-1500314505490 Content-Disposition: form-data; name=”picture”; filename=”” Content-Type: image/jpeg JFIF .)10.)-,3:J>36F7,-@WAFLNRSR2>ZaZP`JQRO &O5-5OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO $3br %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz &'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz Zm-+ n)qKE &)h aCH J)1L iqJ( – 4s@ E P E bJ)? 1R…………………………………………………………………………………………………………………………..”