Professional Documents
Culture Documents
Android Uploading Camera Image, Video To Server With Progress Bar PDF
Android Uploading Camera Image, Video To Server With Progress Bar PDF
AndroidUploadingCameraImage,VideotoServerwithProgressBar
PromoteYourApp
Now
HighCVR+Innovative
MobileAds.100%Non
IncentTraffic.StartNow!
AdvertiseHere
flawlessly.
DOWNLOAD CODE
VIDEO DEMO
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
1/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
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.
STRINGS.XML
<?xmlversion="1.0"encoding="utf8"?>
<resources>
<stringname="app_name">CameraFileUpload</string>
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
2/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
<stringname="btnTakePicture">CaptureImage</string>
<stringname="btnRecordVideo">RecordVideo</string>
<stringname="or">(or)</string>
<stringname="btnUploadToServer">UploadtoServer</string>
</resources>
3. Add below color values in colors.xml located under res values folder.
COLORS.XML
<?xmlversion="1.0"encoding="utf8"?>
<resources>
<colorname="view_background">#e8ecfa</color>
<colorname="btn_bg">#277bec</color>
<colorname="white">#ffffff</color>
<colorname="txt_font">#4e5572</color>
<colorname="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.
CONFIG.JAVA
packageinfo.androidhive.camerafileupload;
publicclassConfig{
//Fileuploadurl(replacetheipwithyourserveraddress)
publicstaticfinalStringFILE_UPLOAD_URL="http://192.168.0.104/AndroidFileUpload
//Directorynametostorecapturedimagesandvideos
publicstaticfinalStringIMAGE_DIRECTORY_NAME="AndroidFileUpload";
}
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.
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
3/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
ANDROIDMULTIPARTENTITY.JAVA
packageinfo.androidhive.camerafileupload;
importjava.io.FilterOutputStream;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.nio.charset.Charset;
importorg.apache.http.entity.mime.HttpMultipartMode;
importorg.apache.http.entity.mime.MultipartEntity;
@SuppressWarnings("deprecation")
publicclassAndroidMultiPartEntityextendsMultipartEntity
privatefinalProgressListenerlistener;
publicAndroidMultiPartEntity(finalProgressListenerlistener){
super();
this.listener=listener;
}
publicAndroidMultiPartEntity(finalHttpMultipartModemode,
finalProgressListenerlistener){
super(mode);
this.listener=listener;
}
publicAndroidMultiPartEntity(HttpMultipartModemode,finalStringboundary,
finalCharsetcharset,finalProgressListenerlistener){
super(mode,boundary,charset);
this.listener=listener;
}
@Override
publicvoidwriteTo(finalOutputStreamoutstream)throwsIOException{
super.writeTo(newCountingOutputStream(outstream,this.listener));
}
publicstaticinterfaceProgressListener{
voidtransferred(longnum);
}
publicstaticclassCountingOutputStreamextendsFilterOutputStream{
privatefinalProgressListenerlistener;
privatelongtransferred;
publicCountingOutputStream(finalOutputStreamout,
finalProgressListenerlistener){
super(out);
this.listener=listener;
this.transferred=0;
}
publicvoidwrite(byte[]b,intoff,intlen)throwsIOException{
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
4/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
out.write(b,off,len);
this.transferred+=len;
this.listener.transferred(this.transferred);
}
publicvoidwrite(intb)throwsIOException{
out.write(b);
this.transferred++;
this.listener.transferred(this.transferred);
}
}
}
Now well 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. Well create it in few minutes.
INT ER NE T Required to make network calls
W RITE _ E X TE RNA L_ STO RA GE Required to store image/video on to storage
RE CO RD _ AU DIO Required to record audio along with video
ANDROIDMANIFEST.XML
<?xmlversion="1.0"encoding="utf8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="info.androidhive.camerafileupload"
android:versionCode="1"
android:versionName="1.0">
<usessdk
android:minSdkVersion="11"
android:targetSdkVersion="21"/>
<usespermissionandroid:name="android.permission.INTERNET"/>
<usespermissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<usespermissionandroid: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">
<intentfilter>
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
5/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
<actionandroid:name="android.intent.action.MAIN"/>
<categoryandroid:name="android.intent.category.LAUNCHER"/>
</intentfilter>
</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.
ACTIVITY_MAIN.XML
<?xmlversion="1.0"encoding="utf8"?>
<RelativeLayoutxmlns: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">
<!Capturepicturebutton>
<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"
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
6/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
android:text="@string/or"
android:textColor="@color/txt_font"/>
<!Recordvideobutton>
<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.
MAINACTIVITY.JAVA
packageinfo.androidhive.camerafileupload;
importjava.io.File;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.Locale;
importandroid.app.Activity;
importandroid.content.Intent;
importandroid.content.pm.PackageManager;
importandroid.graphics.Color;
importandroid.graphics.drawable.ColorDrawable;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.os.Environment;
importandroid.provider.MediaStore;
importandroid.util.Log;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.Toast;
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
7/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
publicclassMainActivityextendsActivity{
//LogCattag
privatestaticfinalStringTAG=MainActivity.class.getSimpleName();
//Cameraactivityrequestcodes
privatestaticfinalintCAMERA_CAPTURE_IMAGE_REQUEST_CODE=100;
privatestaticfinalintCAMERA_CAPTURE_VIDEO_REQUEST_CODE=200;
publicstaticfinalintMEDIA_TYPE_IMAGE=1;
publicstaticfinalintMEDIA_TYPE_VIDEO=2;
privateUrifileUri;//fileurltostoreimage/video
privateButtonbtnCapturePicture,btnRecordVideo;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Changingactionbarbackgroundcolor
//Thesetwolinesarenotneeded
getActionBar().setBackgroundDrawable(newColorDrawable(Color.parseColor(getResou
btnCapturePicture=(Button)findViewById(R.id.btnCapturePicture);
btnRecordVideo=(Button)findViewById(R.id.btnRecordVideo);
/**
*Captureimagebuttonclickevent
*/
btnCapturePicture.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(Viewv){
//capturepicture
captureImage();
}
});
/**
*Recordvideobuttonclickevent
*/
btnRecordVideo.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(Viewv){
//recordvideo
recordVideo();
}
});
//Checkingcameraavailability
if(!isDeviceSupportCamera()){
Toast.makeText(getApplicationContext(),
"Sorry!Yourdevicedoesn'tsupportcamera",
Toast.LENGTH_LONG).show();
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
8/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
//willclosetheappifthedevicedoes'thavecamera
finish();
}
}
/**
*Checkingdevicehascamerahardwareornot
**/
privatebooleanisDeviceSupportCamera(){
if(getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)){
//thisdevicehasacamera
returntrue;
}else{
//nocameraonthisdevice
returnfalse;
}
}
/**
*Launchingcameraapptocaptureimage
*/
privatevoidcaptureImage(){
Intentintent=newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri=getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);
//starttheimagecaptureIntent
startActivityForResult(intent,CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
*Launchingcameraapptorecordvideo
*/
privatevoidrecordVideo(){
Intentintent=newIntent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri=getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
//setvideoquality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
intent.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);//settheimagefile
//name
//startthevideocaptureIntent
startActivityForResult(intent,CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
*Herewestorethefileurlasitwillbenullafterreturningfromcamera
*app
*/
@Override
protectedvoidonSaveInstanceState(BundleoutState){
super.onSaveInstanceState(outState);
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
9/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
//savefileurlinbundleasitwillbenullonscreenorientation
//changes
outState.putParcelable("file_uri",fileUri);
}
@Override
protectedvoidonRestoreInstanceState(BundlesavedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
//getthefileurl
fileUri=savedInstanceState.getParcelable("file_uri");
}
/**
*Receivingactivityresultmethodwillbecalledafterclosingthecamera
**/
@Override
protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
//iftheresultiscapturingImage
if(requestCode==CAMERA_CAPTURE_IMAGE_REQUEST_CODE){
if(resultCode==RESULT_OK){
//successfullycapturedtheimage
//launchinguploadactivity
launchUploadActivity(true);
}elseif(resultCode==RESULT_CANCELED){
//usercancelledImagecapture
Toast.makeText(getApplicationContext(),
"Usercancelledimagecapture",Toast.LENGTH_SHORT)
.show();
}else{
//failedtocaptureimage
Toast.makeText(getApplicationContext(),
"Sorry!Failedtocaptureimage",Toast.LENGTH_SHORT)
.show();
}
}elseif(requestCode==CAMERA_CAPTURE_VIDEO_REQUEST_CODE){
if(resultCode==RESULT_OK){
//videosuccessfullyrecorded
//launchinguploadactivity
launchUploadActivity(false);
}elseif(resultCode==RESULT_CANCELED){
//usercancelledrecording
Toast.makeText(getApplicationContext(),
"Usercancelledvideorecording",Toast.LENGTH_SHORT)
.show();
}else{
//failedtorecordvideo
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
10/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
Toast.makeText(getApplicationContext(),
"Sorry!Failedtorecordvideo",Toast.LENGTH_SHORT)
.show();
}
}
}
privatevoidlaunchUploadActivity(booleanisImage){
Intenti=newIntent(MainActivity.this,UploadActivity.class);
i.putExtra("filePath",fileUri.getPath());
i.putExtra("isImage",isImage);
startActivity(i);
}
/**
*HelperMethods
**/
/**
*Creatingfileuritostoreimage/video
*/
publicUrigetOutputMediaFileUri(inttype){
returnUri.fromFile(getOutputMediaFile(type));
}
/**
*returningimage/video
*/
privatestaticFilegetOutputMediaFile(inttype){
//Externalsdcardlocation
FilemediaStorageDir=newFile(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURE
Config.IMAGE_DIRECTORY_NAME);
//Createthestoragedirectoryifitdoesnotexist
if(!mediaStorageDir.exists()){
if(!mediaStorageDir.mkdirs()){
Log.d(TAG,"Oops!Failedcreate"
+Config.IMAGE_DIRECTORY_NAME+"directory");
returnnull;
}
}
//Createamediafilename
StringtimeStamp=newSimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(newDate());
FilemediaFile;
if(type==MEDIA_TYPE_IMAGE){
mediaFile=newFile(mediaStorageDir.getPath()+File.separator
+"IMG_"+timeStamp+".jpg");
}elseif(type==MEDIA_TYPE_VIDEO){
mediaFile=newFile(mediaStorageDir.getPath()+File.separator
+"VID_"+timeStamp+".mp4");
}else{
returnnull;
}
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
11/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
returnmediaFile;
}
}
Now if you run the app, you should see following output.
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
12/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
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.
ACTIVITY_UPLOAD.XML
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
13/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
<?xmlversion="1.0"encoding="utf8"?>
<LinearLayoutxmlns: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">
<!Todisplaypicturetaken>
<ImageView
android:id="@+id/imgPreview"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:visibility="gone"
android:layout_marginTop="15dp"/>
<!Videoviewtopreviewrecordedvideo>
<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>
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
14/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
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.
UPLOADACTIVITY.JAVA
packageinfo.androidhive.camerafileupload;
importinfo.androidhive.camerafileupload.AndroidMultiPartEntity.ProgressListener;
importjava.io.File;
importjava.io.IOException;
importorg.apache.http.HttpEntity;
importorg.apache.http.HttpResponse;
importorg.apache.http.client.ClientProtocolException;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.entity.mime.content.FileBody;
importorg.apache.http.entity.mime.content.StringBody;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.util.EntityUtils;
importandroid.app.Activity;
importandroid.app.AlertDialog;
importandroid.content.DialogInterface;
importandroid.content.Intent;
importandroid.graphics.Bitmap;
importandroid.graphics.BitmapFactory;
importandroid.graphics.Color;
importandroid.graphics.drawable.ColorDrawable;
importandroid.os.AsyncTask;
importandroid.os.Bundle;
importandroid.util.Log;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.ImageView;
importandroid.widget.ProgressBar;
importandroid.widget.TextView;
importandroid.widget.Toast;
importandroid.widget.VideoView;
publicclassUploadActivityextendsActivity{
//LogCattag
privatestaticfinalStringTAG=MainActivity.class.getSimpleName();
privateProgressBarprogressBar;
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
15/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
privateStringfilePath=null;
privateTextViewtxtPercentage;
privateImageViewimgPreview;
privateVideoViewvidPreview;
privateButtonbtnUpload;
longtotalSize=0;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
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);
//Changingactionbarbackgroundcolor
getActionBar().setBackgroundDrawable(
newColorDrawable(Color.parseColor(getResources().getString(
R.color.action_bar))));
//Receivingthedatafrompreviousactivity
Intenti=getIntent();
//imageorvideopaththatiscapturedinpreviousactivity
filePath=i.getStringExtra("filePath");
//booleanflagtoidentifythemediatype,imageorvideo
booleanisImage=i.getBooleanExtra("isImage",true);
if(filePath!=null){
//Displayingtheimageorvideoonthescreen
previewMedia(isImage);
}else{
Toast.makeText(getApplicationContext(),
"Sorry,filepathismissing!",Toast.LENGTH_LONG).show();
}
btnUpload.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(Viewv){
//uploadingthefiletoserver
newUploadFileToServer().execute();
}
});
/**
*Displayingcapturedimage/videoonthescreen
**/
privatevoidpreviewMedia(booleanisImage){
//Checkingwhethercapturedmediaisimageorvideo
if(isImage){
imgPreview.setVisibility(View.VISIBLE);
vidPreview.setVisibility(View.GONE);
//bimatpfactory
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
16/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
BitmapFactory.Optionsoptions=newBitmapFactory.Options();
//downsizingimageasitthrowsOutOfMemoryExceptionforlarger
//images
options.inSampleSize=8;
finalBitmapbitmap=BitmapFactory.decodeFile(filePath,options);
imgPreview.setImageBitmap(bitmap);
}else{
imgPreview.setVisibility(View.GONE);
vidPreview.setVisibility(View.VISIBLE);
vidPreview.setVideoPath(filePath);
//startplaying
vidPreview.start();
}
}
/**
*Uploadingthefiletoserver
**/
privateclassUploadFileToServerextendsAsyncTask<Void,Integer,String>{
@Override
protectedvoidonPreExecute(){
//settingprogressbartozero
progressBar.setProgress(0);
super.onPreExecute();
}
@Override
protectedvoidonProgressUpdate(Integer...progress){
//Makingprogressbarvisible
progressBar.setVisibility(View.VISIBLE);
//updatingprogressbarvalue
progressBar.setProgress(progress[0]);
//updatingpercentagevalue
txtPercentage.setText(String.valueOf(progress[0])+"%");
}
@Override
protectedStringdoInBackground(Void...params){
returnuploadFile();
}
@SuppressWarnings("deprecation")
privateStringuploadFile(){
StringresponseString=null;
HttpClienthttpclient=newDefaultHttpClient();
HttpPosthttppost=newHttpPost(Config.FILE_UPLOAD_URL);
try{
AndroidMultiPartEntityentity=newAndroidMultiPartEntity(
newProgressListener(){
@Override
publicvoidtransferred(longnum){
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
17/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
publishProgress((int)((num/(float)totalSize)*
}
});
FilesourceFile=newFile(filePath);
//Addingfiledatatohttpbody
entity.addPart("image",newFileBody(sourceFile));
//Extraparametersifyouwanttopasstoserver
entity.addPart("website",
newStringBody("www.androidhive.info"));
entity.addPart("email",newStringBody("abc@gmail.com"));
totalSize=entity.getContentLength();
httppost.setEntity(entity);
//Makingservercall
HttpResponseresponse=httpclient.execute(httppost);
HttpEntityr_entity=response.getEntity();
intstatusCode=response.getStatusLine().getStatusCode();
if(statusCode==200){
//Serverresponse
responseString=EntityUtils.toString(r_entity);
}else{
responseString="Erroroccurred!HttpStatusCode:"
+statusCode;
}
}catch(ClientProtocolExceptione){
responseString=e.toString();
}catch(IOExceptione){
responseString=e.toString();
}
returnresponseString;
@Override
protectedvoidonPostExecute(Stringresult){
Log.e(TAG,"Responsefromserver:"+result);
//showingtheserverresponseinanalertdialog
showAlert(result);
super.onPostExecute(result);
}
/**
*Methodtoshowalertdialog
**/
privatevoidshowAlert(Stringmessage){
AlertDialog.Builderbuilder=newAlertDialog.Builder(this);
builder.setMessage(message).setTitle("ResponsefromServers")
.setCancelable(false)
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
18/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
.setPositiveButton("OK",newDialogInterface.OnClickListener(){
publicvoidonClick(DialogInterfacedialog,intid){
//donothing
}
});
AlertDialogalert=builder.create();
alert.show();
}
Until now we are done with android project. Now lets 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.
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
19/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
upload_max_filesize=50M
post_max_size=50M
max_input_time=300
max_execution_time=300
3. Now restart the WAMP server.
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
20/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
FILEUPLOAD.PHP
<?php
//Pathtomoveuploadedfiles
$target_path="uploads/";
//arrayforfinaljsonrespone
$response=array();
//gettingserveripaddress
$server_ip=gethostbyname(gethostname());
//finalfileurlthatisbeinguploaded
$file_upload_url='http://'.$server_ip.'/'.'AndroidFileUpload'.'/'.$target_pa
if(isset($_FILES['image']['name'])){
$target_path=$target_path.basename($_FILES['image']['name']);
//readingotherpostparameters
$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{
//Throwsexceptionincasefileisnotbeingmoved
if(!move_uploaded_file($_FILES['image']['tmp_name'],$target_path)){
//makeerrorflagtrue
$response['error']=true;
$response['message']='Couldnotmovethefile!';
}
//Filesuccessfullyuploaded
$response['message']='Fileuploadedsuccessfully!';
$response['error']=false;
$response['file_path']=$file_upload_url.basename($_FILES['image']['name'
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
21/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
}catch(Exception$e){
//Exceptionoccurred.Makeerrorflagtrue
$response['error']=true;
$response['message']=$e>getMessage();
}
}else{
//Fileparameterismissing
$response['error']=true;
$response['message']='Notreceivedanyfile!F';
}
//Echofinaljsonresponsetoclient
echojson_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":"Fileuploadedsuccessfully!",
"error":false,
"file_path":"http://192.168.0.104/AndroidFileUpload/uploads/DSC_0021.JPG"
}
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
22/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
23/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
24/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
References
1. Stackoverflow Question about file upload with progress bar.
2. Icon that I used as app icon.
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
25/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
65
Like
24
112
Tweet
Android Downloading
Bar
MySQL Part 2
Page
Android Integrating
Ravi Tamada
Hyderabad, INDIA
SUBSCRIBE
Advertise
AdvertiseHere
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
26/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
AndroidHive
30,968likes
LikePage
ContactUs
1friendlikesthis
Tag Cloud
Action Bar
Apps
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
Adapter
Async
Animation
Beginner
API
Camera
27/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
Chat
Dashboard
File Upload
Fragments
Gestures
Google Plus
HTTP
MySQL
Locale
Material Design
RecyclerView
sessions
Speech Input
SQLite
UI
View Pager
Quick Tips
REST
Sockets
sponsored
PayPal
Progress Bar
Push Notifications
SMS
Grid View
Navigation Drawer
Pinch
GDK
json
List View
Maps
GCM
Grid
Intermediate
Location
Google Glass
GPS
Libstreaming
PHP
Database
Swipe
Video
Volley
Slim
Spinner
Tab View
Video Streaming
Wearable
xml
YouTube
Ravi Tamada
google.com/+RaviTamada
Theo di
13.231 ngi theo di
Most Popular
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
28/30
13/8/2015
AndroidUploadingCameraImage,VideotoServerwithProgressBar
Android
Sliding
Menu
using
Navigation
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
29/30
13/8/2015
Copyright AndroidHive
AndroidUploadingCameraImage,VideotoServerwithProgressBar
http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/
30/30