My previous tutorial explains how to download a file by showing a progress bar. In this commodity I am going to explain how to upload a file to server by showing the progress bar. Using this tutorial you lot 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 item location.

The all-time thing about this commodity is, it works well with larger file uploads too without any out of retention errors. I take tested the app by uploading 50MB file flawlessly.

android file upload with progress bar

Prerequisite

Every bit this commodity uploads the image/video taken from camera, you need to take knowledge over android camera module. So I recommend y'all go through my previous tutorial Android Working with Camera which gives yous an overview of integrating camera in your android apps.

i. Creating Android Project

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

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

<?xml version="i.0" encoding="utf-8"?> <resource>      <string proper name="app_name">Camera File Upload</string>     <string name="btnTakePicture">Capture Paradigm</string>     <string name="btnRecordVideo">Record Video</string>     <string name="or">(or)</string>     <cord name="btnUploadToServer">Upload to Server</string>  </resource>        

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

<?xml version="1.0" encoding="utf-8"?> <resources>      <color proper name="view_background">#e8ecfa</color>     <color name="btn_bg">#277bec</colour>     <color name="white">#ffffff</colour>     <color name="txt_font">#4e5572</color>     <colour 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 volition take to replace the file upload url with yours while testing.

package info.androidhive.camerafileupload;  public grade 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 proper noun to store captured images and videos     public static concluding Cord IMAGE_DIRECTORY_NAME = "Android File Upload"; }        

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

package info.androidhive.camerafileupload;  import java.io.FilterOutputStream; import coffee.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(concluding ProgressListener listener) { 		super(); 		this.listener = listener; 	}  	public AndroidMultiPartEntity(terminal HttpMultipartMode mode, 			final ProgressListener listener) { 		super(style); 		this.listener = listener; 	}  	public AndroidMultiPartEntity(HttpMultipartMode style, terminal String boundary, 			last Charset charset, last 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(last 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); 		} 	} }        

At present we'll add photographic camera support in our app past creating a simple screen with 2 buttons to invoke camera app to capture paradigm or record video.

vi. Open your AndroidManifest.xml file and add required permissions. You lot can notice that UploadActivity also added in beneath manifest file. Nosotros'll create it in few minutes.

Net – 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="one.0" encoding="utf-viii"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="info.androidhive.camerafileupload"     android:versionCode="one"     android:versionName="one.0" >      <uses-sdk         android:minSdkVersion="eleven"         android:targetSdkVersion="21" />      <uses-permission android:name="android.permission.INTERNET" />     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />     <uses-permission android:proper name="android.permission.RECORD_AUDIO" />      <awarding         android:allowBackup="true"         android:icon="@drawable/ic_launcher"         android:label="@string/app_name"         android:theme="@style/AppTheme" >         <action             android:name="info.androidhive.camerafileupload.MainActivity"             android:characterization="@string/app_name"             android:screenOrientation="portrait" >             <intent-filter>                 <action android:name="android.intent.activity.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>         <activity             android:name="info.androidhive.camerafileupload.UploadActivity"             android:screenOrientation="portrait" >         </action>     </awarding>  </manifest>        

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

<?xml version="ane.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:groundwork="@color/view_background"     android:baselineAligned="imitation"     android:orientation="vertical" >      <LinearLayout         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:layout_centerInParent="truthful"         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:groundwork="@color/btn_bg"             android:paddingLeft="20dp"             android:paddingRight="20dp"             android:text="@string/btnTakePicture"             android:textColor="@colour/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="@colour/btn_bg"             android:paddingLeft="20dp"             android:paddingRight="20dp"             android:text="@string/btnRecordVideo"             android:textColor="@colour/white" />     </LinearLayout>  </RelativeLayout>        

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

In brief what this activity will practice is,

> Camera app will be launched on tapping accept picture or tape video button.
> Once the paradigm / video is captured, information technology 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.

packet info.androidhive.camerafileupload;  import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import coffee.util.Locale;  import android.app.Action; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.bone.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 terminal String TAG = MainActivity.class.getSimpleName(); 	       // Camera activity request codes     private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;     private static last int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;          public static last int MEDIA_TYPE_IMAGE = i;     public static concluding int MEDIA_TYPE_VIDEO = two;       individual Uri fileUri; // file url to store image/video          private Push button btnCapturePicture, btnRecordVideo;       @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);                  // Irresolute action bar background colour         // These 2 lines are not needed         getActionBar().setBackgroundDrawable(new ColorDrawable(Colour.parseColor(getResources().getString(R.color.action_bar))));           btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);         btnRecordVideo = (Push) 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 photographic camera availability         if (!isDeviceSupportCamera()) {             Toast.makeText(getApplicationContext(),                     "Distressing! Your device doesn't support camera",                     Toast.LENGTH_LONG).prove();             // will close the app if the device does't have photographic camera             finish();         }     }       /**      * Checking device has photographic 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             render 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 prototype capture Intent         startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);     }          /**      * Launching camera app to tape video      */     private void recordVideo() {         Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);           fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);           // set up 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);     }       /**      * Hither nosotros store the file url every bit it will be null after returning from photographic camera      * app      */     @Override     protected void onSaveInstanceState(Parcel outState) {         super.onSaveInstanceState(outState);           // save file url in packet 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 action consequence method will be called after endmost the photographic camera      * */     @Override     protected void onActivityResult(int requestCode, int resultCode, Intent information) {         // if the result is capturing Image         if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {             if (resultCode == RESULT_OK) {                              	// successfully captured the paradigm                 // 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 prototype", Toast.LENGTH_SHORT)                         .evidence();             }                  } 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)                         .prove();                          } 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.form);         i.putExtra("filePath", fileUri.getPath());         i.putExtra("isImage", isImage);         startActivity(i);     }           /**      * ------------ Helper Methods ----------------------       * */       /**      * Creating file uri to shop prototype/video      */     public Uri getOutputMediaFileUri(int blazon) {         return Uri.fromFile(getOutputMediaFile(type));     }       /**      * returning paradigm / video      */     individual static File getOutputMediaFile(int blazon) {           // External sdcard location         File mediaStorageDir = new File(                 Environment                         .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),                 Config.IMAGE_DIRECTORY_NAME);           // Create the storage directory if it does non 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         Cord timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",                 Locale.getDefault()).format(new Appointment());         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 {             render zippo;         }           return mediaFile;     } }        

Now if you lot run the app, yous should see following output.

android-file-upload-camera-screen

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

In one case you are able to launch camera and capture images, we can move forward and start creating the upload activeness.

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:groundwork="@colour/view_background"     android:orientation="vertical"     android:padding="10dp" >            <!-- To brandish 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 grade named UploadActivity.java and paste below code. In this activity

> The path of captured photographic camera prototype/video is received from MainActivity and paradigm/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 coffee.io.File; import java.io.IOException;  import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.customer.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.Colour; import android.graphics.drawable.ColorDrawable; import android.os.AsyncTask; import android.bone.Bundle; import android.util.Log; import android.view.View; import android.widget.Push; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import android.widget.VideoView;  public grade UploadActivity extends Activity { 	// LogCat tag 	private static final String TAG = MainActivity.class.getSimpleName();  	individual 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(Parcel 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(Colour.parseColor(getResources().getString( 						R.color.action_bar))));  		// Receiving the data from previous activity 		Intent i = getIntent();  		// epitome or video path that is captured in previous activity 		filePath = i.getStringExtra("filePath");  		// boolean flag to identify the media type, epitome 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 epitome/video on the screen 	 * */ 	individual void previewMedia(boolean isImage) { 		// Checking whether captured media is prototype 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); 			// kickoff playing 			vidPreview.showtime(); 		} 	}  	/** 	 * Uploading the file to server 	 * */ 	private class UploadFileToServer extends AsyncTask<Void, Integer, Cord> { 		@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 = goose egg;  			HttpClient httpclient = new DefaultHttpClient(); 			HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);  			attempt { 				AndroidMultiPartEntity entity = new AndroidMultiPartEntity( 						new ProgressListener() {  							@Override 							public void transferred(long num) { 								publishProgress((int) ((num / (float) totalSize) * 100)); 							} 						});  				File sourceFile = new File(filePath);  				// Calculation file data to http body 				entity.addPart("paradigm", new FileBody(sourceFile));  				// Extra parameters if you lot want to laissez passer 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 = "Fault occurred! Http Status Code: " 							+ statusCode; 				}  			} grab (ClientProtocolException e) { 				responseString = e.toString(); 			} catch (IOException east) { 				responseString = eastward.toString(); 			}  			return responseString;  		}  		@Override 		protected void onPostExecute(Cord consequence) { 			Log.due east(TAG, "Response from server: " + consequence);  			// showing the server response in an alert dialog 			showAlert(result);  			super.onPostExecute(consequence); 		}  	}  	/** 	 * Method to show alarm dialog 	 * */ 	private void showAlert(Cord message) { 		AlertDialog.Architect architect = 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) { 						// practise cypher 					} 				}); 		AlertDialog alarm = builder.create(); 		alarm.show(); 	}  }        

Until at present we are done with android project. At present let's apace create the PHP project to receive the file that is being sent from android app. Simply earlier that, nosotros need to practice modest configuration changes to WAMP server.

ii. Installing & Configuring WAMP Server

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

two. Open php.ini and modify beneath values. By default wamp server allows maximum of 2MB file only to upload. After irresolute the below values, you tin 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. At present restart the WAMP server.

3. Creating PHP Project

1. Become inside C:\wamp\www and create a binder 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.

three. 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 bulletin.

<?php  // Path to motion 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 mail parameters     $electronic mail = isset($_POST['email']) ? $_POST['email'] : '';     $website = isset($_POST['website']) ? $_POST['website'] : '';      $response['file_name'] = basename($_FILES['image']['name']);     $response['electronic mail'] = $email;     $response['website'] = $website;      try {         // Throws exception incase file is not beingness moved         if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {             // brand fault 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'] = $eastward->getMessage();     } } else {     // File parameter is missing     $response['error'] = true;     $response['message'] = 'Not received any file!F'; }  // Repeat last json response to client echo json_encode($response); ?>        

Beneath 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 lot how to test the both apps together locally.

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

2. Beginning the WAMP server.

3. Get the ip address of the auto that is running the PHP project. Yous can go the ip accost past typing ipconfig in command prompt. (On mac os, employ ifconfig to go the ip accost)

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

five. 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
ane. Stackoverflow Question about file upload with progress bar.

2. Icon that I used as app icon.