java - Android Uploading Camera Image, Video to php Server -
i trying capture image or record video using camera , upload server. on server side, used php language read file , moved particular location.
this php script
<?php // path move uploaded files $target_path = "uploads/"; // array final json respone $response = array(); // getting server ip address $server_ip = gethostbyname(gethostname()); // final file url 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 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 file!'; } // file 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 missing $response['error'] = true; $response['message'] = 'not received file!f'; } // echo final json response client echo json_encode($response); ?>
and got php error
i not have experience in php coding, want know what's wrong php.
the android client complete run, can take photo , video well, upload completed, got nothing in server client folder.
there android code:
mainactivity.java
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 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 2 lines 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! device doesn't support camera", toast.length_long).show(); // close app if device does't have camera finish(); } } /** * checking device has camera hardware or not * */ private boolean isdevicesupportcamera() { if (getapplicationcontext().getpackagemanager().hassystemfeature( packagemanager.feature_camera)) { // device has camera return true; } else { // no camera on device return false; } } /** * launching camera app 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 image capture intent startactivityforresult(intent, camera_capture_image_request_code); } /** * launching camera app 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 image file // name // start video capture intent startactivityforresult(intent, camera_capture_video_request_code); } /** * here store file url null after returning camera * app */ @override protected void onsaveinstancestate(bundle outstate) { super.onsaveinstancestate(outstate); // save file url in bundle null on screen orientation // changes outstate.putparcelable("file_uri", fileuri); } @override protected void onrestoreinstancestate(bundle savedinstancestate) { super.onrestoreinstancestate(savedinstancestate); // file url fileuri = savedinstancestate.getparcelable("file_uri"); } /** * receiving activity result method called after closing camera * */ @override protected void onactivityresult(int requestcode, int resultcode, intent data) { // if result capturing image if (requestcode == camera_capture_image_request_code) { if (resultcode == result_ok) { // captured 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 capture image toast.maketext(getapplicationcontext(), "sorry! failed capture image", toast.length_short) .show(); } } else if (requestcode == camera_capture_video_request_code) { if (resultcode == result_ok) { // video 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 record video toast.maketext(getapplicationcontext(), "sorry! failed record video", toast.length_short) .show(); } } } private void launchuploadactivity(boolean isimage){ intent = new intent(mainactivity.this, uploadactivity.class); i.putextra("filepath", fileuri.getpath()); i.putextra("isimage", isimage); startactivity(i); } /** * ------------ helper methods ---------------------- * */ /** * creating file uri 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 storage directory if not exist if (!mediastoragedir.exists()) { if (!mediastoragedir.mkdirs()) { log.d(tag, "oops! failed create " + config.image_directory_name + " directory"); return null; } } // create 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; }
}
config.java
public class config { // file upload url (replace ip server address) public static final string file_upload_url = "http://wangjian.site90.net/androidfileupload/fileupload.php"; // directory name store captured images , videos public static final string image_directory_name = "android file upload";
}
uploadactivity.java
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) { // todo auto-generated method stub 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 data previous activity intent = getintent(); // image or video path captured in previous activity filepath = i.getstringextra("filepath"); // boolean flag identify media type, image or video boolean isimage = i.getbooleanextra("isimage", true); if (filepath != null) { // displaying image or video on screen previewmedia(isimage); } else { toast.maketext(getapplicationcontext(), "sorry, file path missing!", toast.length_long).show(); } btnupload.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { // uploading file server new uploadfiletoserver().execute(); } }); } /** * displaying captured image/video on screen * */ private void previewmedia(boolean isimage) { // checking whether captured media image or video if (isimage) { imgpreview.setvisibility(view.visible); vidpreview.setvisibility(view.gone); // bimatp factory bitmapfactory.options options = new bitmapfactory.options(); // down sizing image throws outofmemory exception 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 file server * */ private class uploadfiletoserver extends asynctask<void, integer, string> { @override protected void onpreexecute() { // setting progress bar 0 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 http body entity.addpart("image", new filebody(sourcefile)); // parameters if want pass 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 server: " + result); // showing server response in alert dialog showalert(result); super.onpostexecute(result); } } /** * method show alert dialog * */ private void showalert(string message) { alertdialog.builder builder = new alertdialog.builder(this); builder.setmessage(message).settitle("response servers") .setcancelable(false) .setpositivebutton("ok", new dialoginterface.onclicklistener() { public void onclick(dialoginterface dialog, int id) { // nothing } }); alertdialog alert = builder.create(); alert.show(); }
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.wangjian.klmeet_photo" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="16" android:targetsdkversion="16" /> <uses-permission android:name="android.permission.internet" /> <uses-permission android:name="android.permission.read_external_storage" /> <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=".mainactivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <activity android:name="com.wangjian.klmeet_photo.uploadactivity" android:screenorientation="portrait" > </activity> </application> </manifest>
this logcat:
06-04 03:53:12.440: e/mainactivity(7920): <b>fatal error</b>: call undefined function gethostname() in <b>/home/a4256838/public_html/androidfileupload/fileupload.php</b> on line <b>10</b><br /> 06-04 03:53:12.440: e/mainactivity(7920): <br><table border='1' cellpadding='2' bgcolor='#ffffdf' bordercolor='#e8b900' align='center'><tr><td><div align='center'><a href='http://www.000webhost.com/'><font face='arial' size='1' color='#000000'>free web hosting</font></a></div></td></tr></table>
i'm newbie @ stuff appreciated. much! , upload more details if needed.
gethostname()
function of php >= 5.3.0 , believe server have php < 5.3.0 instead of gethostname()
use php_uname('n')
or update php version.
<?php // path move uploaded files $target_path = "uploads/"; // array final json respone $response = array(); // getting server ip address $server_ip = gethostbyname(php_uname('n')); // final file url 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 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 file!'; } // file 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 missing $response['error'] = true; $response['message'] = 'not received file!f'; } // echo final json response client echo json_encode($response); ?>
ref. link
Comments
Post a Comment