30
13/8/2015 Android Uploading Camera Image, Video to Server with Progress Bar http://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 1/30 Advertise Here Promote Your App Now High CVR + Innovative Mobile Ads. 100% Non Incent Traffic. Start Now! Android Uploading Camera Image, Video to Server with Progress Bar 213 Comments . By Ravi Tamada . on December 18, 2014 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. DOWNLOAD CODE VIDEO DEMO

Android Uploading Camera Image, Video to Server with Progress Bar.pdf

Embed Size (px)

Citation preview

13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 1/30AdvertiseHerePromoteYourAppNowHighCVR+InnovativeMobileAds.100%NonIncentTraffic.StartNow!Android Uploading Camera Image, Video toServer with Progress Bar213 Comments . By Ravi Tamada . on December 18, 2014My previous tutorial explains how to download a file byshowingaprogressbar.InthisarticleIamgoingtoexplainhowtouploadafiletoserverbyshowingtheprogressbar.Usingthistutorialyoucanbuildanapplike Instagram where you can capture image or recordavideousingcameraandthenuploadtoaserver.Ontheserverside,IusedPHPlanguagetoreadthefileand moved it to a particular location.Thebestthingaboutthisarticleis,itworkswellwithlargerfileuploadstoowithoutanyoutofmemoryerrors.Ihavetestedtheappbyuploading50MBfileflawlessly.DOWNLOAD CODEVIDEO DEMO13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 2/30Android Uploading Camera Image, Video to Server with Progress BarPrerequisiteAs this article uploads the image/video taken from camera, you need to have knowledge over androidcamera module. So I recommend you go through my previous tutorial AndroidWorkingwithCamerawhich gives you an overview of integrating camera in your android apps.1. Creating Android Project1. In Eclipse create a new android project by navigating to File New Android Application Projectand fill out all the required details.2. Open strings.xml located under res values and add below string values.STRINGS.XML

CameraFileUpload13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 3/303. Add below color values in colors.xml located under res values folder.4. Now under src folder create a new class named Config.java. This class file contains file upload URLand image directory name to save the image/video on mobile memory. You will have to replace the fileupload url with yours while testing.5.CreateaclassnamedAndroidMultiPartEntity.javaandpastebelowcode.ThisclassisacustomMultipartEntityclasswhichprovidesveryimportantfunctionalityrequiredforthisprojectsuchasprogress bar incrementation.CaptureImageRecordVideo(or)UploadtoServer

COLORS.XML

#e8ecfa#277bec#ffffff#4e5572#1f2649

CONFIG.JAVApackageinfo.androidhive.camerafileupload;publicclassConfig{//Fileuploadurl(replacetheipwithyourserveraddress)publicstaticfinalStringFILE_UPLOAD_URL="http://192.168.0.104/AndroidFileUpload/fileUpload.php//DirectorynametostorecapturedimagesandvideospublicstaticfinalStringIMAGE_DIRECTORY_NAME="AndroidFileUpload";}13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 4/30ANDROIDMULTIPARTENTITY.JAVApackageinfo.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;}@OverridepublicvoidwriteTo(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{13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 5/30Nowwelladdcamerasupportinourappbycreatingasimplescreenwithtwobuttonstoinvokecamera app to capture image or record video.6.OpenyourAndroidManifest.xmlfileandaddrequiredpermissions.YoucannoticethatUploadActivity also added in below manifest file. Well create it in few minutes.I NTERNET Required to make network callsWRI TE_EXTERNAL_STORAGE Required to store image/video on to storageRECORD_AUDI O Required to record audio along with videoout.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);}}}ANDROIDMANIFEST.XML

13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 6/307.Openthelayoutfileofyourmainactivity(activity_main.xml)andaddbelowcode.Thiscreatesalayout with two buttons.

ACTIVITY_MAIN.XML

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. Theprocess of uploading will be done in UploadActivity.android:text="@string/or"android:textColor="@color/txt_font"/>

MAINACTIVITY.JAVApackageinfo.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;13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 8/30publicclassMainActivityextendsActivity{//LogCattagprivatestaticfinalStringTAG=MainActivity.class.getSimpleName();//CameraactivityrequestcodesprivatestaticfinalintCAMERA_CAPTURE_IMAGE_REQUEST_CODE=100;privatestaticfinalintCAMERA_CAPTURE_VIDEO_REQUEST_CODE=200;publicstaticfinalintMEDIA_TYPE_IMAGE=1;publicstaticfinalintMEDIA_TYPE_VIDEO=2;privateUrifileUri;//fileurltostoreimage/videoprivateButtonbtnCapturePicture,btnRecordVideo;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//Changingactionbarbackgroundcolor//ThesetwolinesarenotneededgetActionBar().setBackgroundDrawable(newColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));btnCapturePicture=(Button)findViewById(R.id.btnCapturePicture);btnRecordVideo=(Button)findViewById(R.id.btnRecordVideo);/***Captureimagebuttonclickevent*/btnCapturePicture.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){//capturepicturecaptureImage();}});/***Recordvideobuttonclickevent*/btnRecordVideo.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){//recordvideorecordVideo();}});//Checkingcameraavailabilityif(!isDeviceSupportCamera()){Toast.makeText(getApplicationContext(),"Sorry!Yourdevicedoesn'tsupportcamera",Toast.LENGTH_LONG).show();13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 9/30//willclosetheappifthedevicedoes'thavecamerafinish();}}/***Checkingdevicehascamerahardwareornot**/privatebooleanisDeviceSupportCamera(){if(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){//thisdevicehasacamerareturntrue;}else{//nocameraonthisdevicereturnfalse;}}/***Launchingcameraapptocaptureimage*/privatevoidcaptureImage(){Intentintent=newIntent(MediaStore.ACTION_IMAGE_CAPTURE);fileUri=getOutputMediaFileUri(MEDIA_TYPE_IMAGE);intent.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);//starttheimagecaptureIntentstartActivityForResult(intent,CAMERA_CAPTURE_IMAGE_REQUEST_CODE);}/***Launchingcameraapptorecordvideo*/privatevoidrecordVideo(){Intentintent=newIntent(MediaStore.ACTION_VIDEO_CAPTURE);fileUri=getOutputMediaFileUri(MEDIA_TYPE_VIDEO);//setvideoqualityintent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);intent.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);//settheimagefile//name//startthevideocaptureIntentstartActivityForResult(intent,CAMERA_CAPTURE_VIDEO_REQUEST_CODE);}/***Herewestorethefileurlasitwillbenullafterreturningfromcamera*app*/@OverrideprotectedvoidonSaveInstanceState(BundleoutState){super.onSaveInstanceState(outState);13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 10/30//savefileurlinbundleasitwillbenullonscreenorientation//changesoutState.putParcelable("file_uri",fileUri);}@OverrideprotectedvoidonRestoreInstanceState(BundlesavedInstanceState){super.onRestoreInstanceState(savedInstanceState);//getthefileurlfileUri=savedInstanceState.getParcelable("file_uri");}/***Receivingactivityresultmethodwillbecalledafterclosingthecamera**/@OverrideprotectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){//iftheresultiscapturingImageif(requestCode==CAMERA_CAPTURE_IMAGE_REQUEST_CODE){if(resultCode==RESULT_OK){//successfullycapturedtheimage//launchinguploadactivitylaunchUploadActivity(true);}elseif(resultCode==RESULT_CANCELED){//usercancelledImagecaptureToast.makeText(getApplicationContext(),"Usercancelledimagecapture",Toast.LENGTH_SHORT).show();}else{//failedtocaptureimageToast.makeText(getApplicationContext(),"Sorry!Failedtocaptureimage",Toast.LENGTH_SHORT).show();}}elseif(requestCode==CAMERA_CAPTURE_VIDEO_REQUEST_CODE){if(resultCode==RESULT_OK){//videosuccessfullyrecorded//launchinguploadactivitylaunchUploadActivity(false);}elseif(resultCode==RESULT_CANCELED){//usercancelledrecordingToast.makeText(getApplicationContext(),"Usercancelledvideorecording",Toast.LENGTH_SHORT).show();}else{//failedtorecordvideo13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 11/30Toast.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){//ExternalsdcardlocationFilemediaStorageDir=newFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),Config.IMAGE_DIRECTORY_NAME);//Createthestoragedirectoryifitdoesnotexistif(!mediaStorageDir.exists()){if(!mediaStorageDir.mkdirs()){Log.d(TAG,"Oops!Failedcreate"+Config.IMAGE_DIRECTORY_NAME+"directory");returnnull;}}//CreateamediafilenameStringtimeStamp=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;}13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 12/30Now if you run the app, you should see following output.returnmediaFile;}}13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 13/30Once you are able to launch camera and capture images, we can move forward and start creating theupload activity.9.Createanxmlfileunderreslayoutfoldernamedactivity_upload.xml.ThislayoutcontainsImageView,VideoViewtopreviewthecapturedmediaandaProgressBartoshowuploadingprogress.ACTIVITY_UPLOAD.XML13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 14/30

13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 15/3010. 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 displayedon the screen for preview purpose.> UploadFileToServer async method takes care of uploading file to server and updating the ProgressBar.UPLOADACTIVITY.JAVApackageinfo.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{//LogCattagprivatestaticfinalStringTAG=MainActivity.class.getSimpleName();privateProgressBarprogressBar;13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 16/30privateStringfilePath=null;privateTextViewtxtPercentage;privateImageViewimgPreview;privateVideoViewvidPreview;privateButtonbtnUpload;longtotalSize=0;@OverrideprotectedvoidonCreate(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);//ChangingactionbarbackgroundcolorgetActionBar().setBackgroundDrawable(newColorDrawable(Color.parseColor(getResources().getString(R.color.action_bar))));//ReceivingthedatafrompreviousactivityIntenti=getIntent();//imageorvideopaththatiscapturedinpreviousactivityfilePath=i.getStringExtra("filePath");//booleanflagtoidentifythemediatype,imageorvideobooleanisImage=i.getBooleanExtra("isImage",true);if(filePath!=null){//DisplayingtheimageorvideoonthescreenpreviewMedia(isImage);}else{Toast.makeText(getApplicationContext(),"Sorry,filepathismissing!",Toast.LENGTH_LONG).show();}btnUpload.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){//uploadingthefiletoservernewUploadFileToServer().execute();}});}/***Displayingcapturedimage/videoonthescreen**/privatevoidpreviewMedia(booleanisImage){//Checkingwhethercapturedmediaisimageorvideoif(isImage){imgPreview.setVisibility(View.VISIBLE);vidPreview.setVisibility(View.GONE);//bimatpfactory13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 17/30BitmapFactory.Optionsoptions=newBitmapFactory.Options();//downsizingimageasitthrowsOutOfMemoryExceptionforlarger//imagesoptions.inSampleSize=8;finalBitmapbitmap=BitmapFactory.decodeFile(filePath,options);imgPreview.setImageBitmap(bitmap);}else{imgPreview.setVisibility(View.GONE);vidPreview.setVisibility(View.VISIBLE);vidPreview.setVideoPath(filePath);//startplayingvidPreview.start();}}/***Uploadingthefiletoserver**/privateclassUploadFileToServerextendsAsyncTask{@OverrideprotectedvoidonPreExecute(){//settingprogressbartozeroprogressBar.setProgress(0);super.onPreExecute();}@OverrideprotectedvoidonProgressUpdate(Integer...progress){//MakingprogressbarvisibleprogressBar.setVisibility(View.VISIBLE);//updatingprogressbarvalueprogressBar.setProgress(progress[0]);//updatingpercentagevaluetxtPercentage.setText(String.valueOf(progress[0])+"%");}@OverrideprotectedStringdoInBackground(Void...params){returnuploadFile();}@SuppressWarnings("deprecation")privateStringuploadFile(){StringresponseString=null;HttpClienthttpclient=newDefaultHttpClient();HttpPosthttppost=newHttpPost(Config.FILE_UPLOAD_URL);try{AndroidMultiPartEntityentity=newAndroidMultiPartEntity(newProgressListener(){@Overridepublicvoidtransferred(longnum){13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 18/30publishProgress((int)((num/(float)totalSize)*}});FilesourceFile=newFile(filePath);//Addingfiledatatohttpbodyentity.addPart("image",newFileBody(sourceFile));//Extraparametersifyouwanttopasstoserverentity.addPart("website",newStringBody("www.androidhive.info"));entity.addPart("email",newStringBody("[email protected]"));totalSize=entity.getContentLength();httppost.setEntity(entity);//MakingservercallHttpResponseresponse=httpclient.execute(httppost);HttpEntityr_entity=response.getEntity();intstatusCode=response.getStatusLine().getStatusCode();if(statusCode==200){//ServerresponseresponseString=EntityUtils.toString(r_entity);}else{responseString="Erroroccurred!HttpStatusCode:"+statusCode;}}catch(ClientProtocolExceptione){responseString=e.toString();}catch(IOExceptione){responseString=e.toString();}returnresponseString;}@OverrideprotectedvoidonPostExecute(Stringresult){Log.e(TAG,"Responsefromserver:"+result);//showingtheserverresponseinanalertdialogshowAlert(result);super.onPostExecute(result);}}/***Methodtoshowalertdialog**/privatevoidshowAlert(Stringmessage){AlertDialog.Builderbuilder=newAlertDialog.Builder(this);builder.setMessage(message).setTitle("ResponsefromServers").setCancelable(false)13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 19/30Until now we are done with android project. Now lets quickly create the PHP project to receive the filethatisbeingsentfromandroidapp.Butbeforethat,weneedtodosmallconfigurationchangestoWAMP server.2. Installing & Configuring WAMP Server1.DownloadandinstallWAMPsoftware.Onwindowsmachine,WAMPwillbeinstalledatC:\wamplocation.2. Open php.ini and modify below values. By default wamp server allows maximum of 2MB file only toupload. After changing the below values, you can upload the files upto 50MB size..setPositiveButton("OK",newDialogInterface.OnClickListener(){publicvoidonClick(DialogInterfacedialog,intid){//donothing}});AlertDialogalert=builder.create();alert.show();}}13/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 20/303. Now restart the WAMP server.upload_max_filesize=50Mpost_max_size=50Mmax_input_time=300max_execution_time=30013/8/2015 AndroidUploadingCameraImage,VideotoServerwithProgressBarhttp://www.androidhive.info/2014/12/androiduploadingcameraimagevideotoserverwithprogressbar/ 21/303. Creating PHP Project1.GoinsideC:\wamp\wwwandcreateafoldernamedAndroidFileUpload.Thiswillbetherootdirectory of our project.2. Now go into AndroidFileUpload folder and create a folder named uploads to keep all the uploadedfiles.3.CreateafilenamedfileUpload.phpandpastebelowcontent.Belowphpcodetakescareofreceivingthefilesfromandroidappandstoretheminuploadsfolder.Upontheprocessingthefile,server responds with a JSON message.FILEUPLOAD.PHP