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.

Subscribe
Notify of
guest
586 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Gustavo Henrique
5 years ago

Excellent job. Could teach how to send MP3 audio.

Ravi Tamada
5 years ago

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

sreeshty raychoudhury
sreeshty raychoudhury
5 years ago
Reply to  Ravi Tamada

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
mishael95
5 years ago

Nice one mate

waytoweb jain
waytoweb jain
5 years ago

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
Jackson Pollocks
5 years ago
Reply to  waytoweb jain

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

dan julian
dan julian
5 years ago

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

Ravi Tamada
5 years ago
Reply to  dan julian

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

waytoweb jain
waytoweb jain
5 years ago

thank ravi, its working now. realy thank you

Rudi
Rudi
5 years ago

thanks ravi, I really like the tutorial you

Harish A
Harish A
5 years ago

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

Ravi Tamada
5 years ago
Reply to  Harish A

You will receive a json message from server as push notification in which picture url will be presented. Then you have to download the image.
http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/

Dung
Dung
5 years ago

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
Ahmad
5 years ago

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
Korey
5 years ago

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

waytoweb jain
waytoweb jain
5 years ago

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
Vipul Thawre
5 years ago

nice sir

sangu
sangu
5 years ago

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

Muhammad Zubair
Muhammad Zubair
5 years ago

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

MD Danish Ansari
MD Danish Ansari
5 years ago

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.

Ravi Tamada
5 years ago

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

MD Danish Ansari
MD Danish Ansari
5 years ago
Reply to  Ravi Tamada

thanks big bro…:)

Guest
Guest
5 years ago
Reply to  Ravi Tamada

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
badname
5 years ago

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
badname
5 years ago

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

Ravi Tamada
5 years ago
Reply to  badname

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

Korey
Korey
5 years ago

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

Jaydeep Goyani
Jaydeep Goyani
5 years ago

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

Jaydeep Goyani
Jaydeep Goyani
5 years ago

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

jaydeep
jaydeep
5 years ago
Reply to  Jaydeep Goyani

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

gives error

Vineeth KK
Vineeth KK
4 years ago
Reply to  jaydeep

Just remove this line

Marcos Campos
Marcos Campos
5 years ago

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

Guest
Guest
5 years ago

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

Bhagyasri Patel
Bhagyasri Patel
5 years ago

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
Amadeus Prime
5 years ago

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

Bhagyasri Patel
Bhagyasri Patel
5 years ago
Reply to  Amadeus Prime

Thank you so much for your help…I have followed all the steps..But still i am getting the same error…The link http://192.168.1.102/AndroidFileUpload/fileUpload.php is working from browser but from android phone it is not working…

Ravi Tamada
5 years ago

Everytime you restart the router, the ip address may change. Please verify the ip address once again. If that is correct, your mobile not able to access the PC on which server is running on.

Use the below app and do a ping ‘your_ip_address’. You should see some data received. If not you have a problem in router.

https://play.google.com/store/apps/details?id=com.ulfdittmer.android.ping&hl=en

amadeus
amadeus
5 years ago
Reply to  Ravi Tamada

Just type it as below:

type the ip address followed by “:” and the port of your remote server by default its 80 or if you changed it please type the port after the ip address
http://192.168.1.102:80/AndroidFileUpload/fileUpload.php

EmileH2000
EmileH2000
5 years ago

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
Ralfh
5 years ago

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;

Ravi Tamada
5 years ago
Reply to  Ralfh

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
ralfh
5 years ago
Reply to  Ravi Tamada

I got it now,. Thanks for the response!

MD Danish Ansari
MD Danish Ansari
5 years ago

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
Navi
5 years ago

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
Amadeus
5 years ago

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
Benny
5 years ago

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
Prathibha Nandini
5 years ago
Reply to  Benny

is there any solution for this scenario??

Ralfh
Ralfh
5 years ago

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
Pedro
5 years ago

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

javax.net.ssl.sslpeerunverifiedexception no peer certificate

Please help me. Thanks.

RK
RK
5 years ago

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

Kevin Christie
Kevin Christie
5 years ago

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
Shanni
5 years ago

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
Jed Dilag
5 years ago
Reply to  Shanni

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
Shanni
5 years ago
Reply to  Jed Dilag

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
Cloyd Revira
5 years ago

Hi Ravi,

How can I add header token?

Cloyd Revira
Cloyd Revira
5 years ago

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
Andrea
5 years ago

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
Chera Robinson
5 years ago

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
mostafa
5 years ago

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

Chathura Wijesinghe
5 years ago

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

Tindi_
Tindi_
5 years ago

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

Sahitya Kumar Suman
Sahitya Kumar Suman
5 years ago

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
Sahitya Kumar Suman
5 years ago

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

Ravi Tamada
5 years ago

Do you want to generate json from a database?

Sahitya Kumar Suman
Sahitya Kumar Suman
5 years ago
Reply to  Ravi Tamada

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
Sahitya Kumar Suman
5 years ago
Reply to  Ravi Tamada

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
Sahitya Kumar Suman
5 years ago
Reply to  Ravi Tamada

Rply me as soon as possible sir

Ravi Tamada
5 years ago

The best way is to create a REST model for your api. Follow below tutorial
http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-12-2/

Sahitya Kumar Suman
Sahitya Kumar Suman
5 years ago
Reply to  Ravi Tamada

if you get some time then make a small attention on Deployd api creating module succefully created the api with it but not able to understand how to connect that api with database and the server other then localhost …….. please just make a look at it . I will be very much thankfull to you

Regards
Sahitya

Jed Dilag
Jed Dilag
5 years ago

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
Shanni
5 years ago
Reply to  Jed Dilag

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
Rifky Raymond
5 years ago
Reply to  Jed Dilag

you just replace

android:minSdkVersion=”11″

on AndroidManifest.xml file

Vineeth KK
Vineeth KK
4 years ago
Reply to  Jed Dilag

Remove this line will solve problem..

Ankit
Ankit
5 years ago

Hi,

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

Thanks,

Samet
Samet
5 years ago

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
Neji
5 years ago

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

Rege
Rege
5 years ago

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
Prem Nath
5 years ago

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
ashe
5 years ago

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

Manul
Manul
5 years ago

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

586
0
Would love your thoughts, please comment.x
()
x