Android simple implementation to upload phone pictures to the server

Source: Internet
Author: User
Tags parse string

In this example. Will simply implement the Android phone to upload the image to the server. This example uses the server side: Php+apache client: Java first simple implementation of server-side upload and test upload effect, see the example
<?php if (Empty ($_get[' submit ')) {><form enctype= "multipart/form-data" action= "<?php $_server[" PHP_ Self ']?

>?submit=1 "method=" POST ">send this file: <input name=" filename "type=" file "><input type=" Submit "value = "OK upload" ></form><?

php}else{$path = "e:\comsenzexp\wwwroot\uploadfiles/", if (!file_exists ($path)) {mkdir ("$path", 0700);} $file 2 = $path. Time (). ". JPG "; $result = Move_uploaded_file ($_files[" filename "[" Tmp_name "], $file 2); if ($result) {$return = array (' status ' = > ' true ', ' path ' = $file 2);} else{$return = Array (' status ' = ' false ', ' path ' = = $file 2);} echo Json_encode ($return);}? >

In the above code is very easy to upload the image to the server, at the same time it is necessary to note that in the real operation of the code is not able to directly use, there is a lot of other functions to expand it, such as verifying whether the image agrees to upload, verify the size of the image and so on. Next, take a look at the Android main program Mainactivity.java
Package Com.example.androidupload;import Java.io.bytearrayoutputstream;import Java.io.file;import Java.io.ioexception;import Java.io.inputstream;import Org.apache.http.httpresponse;import Org.apache.http.httpstatus;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.multipartentity;import Org.apache.http.entity.mime.content.contentbody;import Org.apache.http.entity.mime.content.filebody;import Org.apache.http.impl.client.defaulthttpclient;import Org.json.jsonexception;import Org.json.jsonobject;import Org.json.jsontokener;import Android.os.Bundle;import Android.os.environment;import Android.os.handler;import Android.app.activity;import Android.util.Log;import Android.view.menu;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.Button; Import Android.widget.textview;import Android.widget.toast;public class Mainactivity extends Activity {Private String imagepath;//the picture path to be uploaded private Handler handler;//will be bound to create his line approached (usually on the main thread) private multipartentity Multipartentity;private Boolean isupload = false;//inferred whether the upload was successful private TextView tv;private String simagepath;// Server side return path @overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); ImagePath = environment.getexternalstoragedirectory () + File.separator+ " Tmp.jpg "; handler = new Handler ();//bind to the main thread in button btn = (button) Findviewbyid (R.id.button1); Btn.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated method Stubnew Thread () {public void Ru N () {File File = new file (imagePath); multipartentity = new multipartentity (); Contentbody contentbody = new Filebody (file, "Image/jpeg"); Multipartentity.addpart ("filename", contentbody); HttpPost HttpPost = new HttpPost ("Http://192.168.1.100/x.php?submit=1"); httppost.setentity (multipartentity); HttpClient HttpClient = nEW defaulthttpclient (); try {HttpResponse HttpResponse = Httpclient.execute (httppost); InputStream in = Httpresponse.getentity (). getcontent (); String content = readString (in), int httpstatus = Httpresponse.getstatusline (). Getstatuscode ();//Get Communication status if (Httpstatus = = HTTPSTATUS.SC_OK) {Jsonobject jsonobject = Parsejson (content);//parse string as JSON object string status = Jsonobject.getstring (" Status ");//get upload state Simagepath = jsonobject.getstring (" path "); LOG.D ("MSG", status), if (Status.equals ("true")) {isupload = true;}} LOG.D ("MSG", content); LOG.D ("MSG", "Upload Success");} catch (Clientprotocolexception e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//TODO Auto-generated catch Blocke.printstacktrace ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Handler.post (New Runnable () {@Overridepublic void Run () {//TODO auto-generated method stubif (isupload) {TV = (TextView) F Indviewbyid (R.id.textview1); Tv.settext (Simagepath); Toast.maketext (MainactivitY.this, "Upload successful", Toast.length_short). Show (); else {toast.maketext (mainactivity.this, "Upload failed", Toast.length_short). Show ();}});}}. Start ();}}); Protected String readString (InputStream in) throws Exception {byte[] data = new Byte[1024];int length = 0; Bytearrayoutputstream bout = new Bytearrayoutputstream (), while (length = in.read (data))! =-1) {bout.write (data, 0, Lengt h);} return new String (Bout.tobytearray (), "GBK");} Protected Jsonobject Parsejson (String str) {Jsontokener jsonparser = new Jsontokener (str); Jsonobject result = Null;try {result = (Jsonobject) jsonparser.nextvalue ()} catch (Jsonexception e) {//TODO Auto-generat Ed catch Blocke.printstacktrace ();} return result;} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.activity_main, menu); return true;}}
Because it is a simple implementation, but also more common understanding, the operation of the network and the general function is not encapsulated, so can directly copy this code into its own application to make a slight change can be directly executed, where the server return path defined here can be changed to the URL path itself, This will enable us to display the photos that were successfully uploaded in the client in the returned activity, and then look at the layout file Activity_main.xml
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Tools:context =". Mainactivity "><textviewandroid:id=" @+id/textview1 "android:layout_width=" Wrap_content "Android:layout_ height= "Wrap_content" android:layout_centerhorizontal= "true" android:layout_centervertical= "true" android:text= "@ String/hello_world "/><buttonandroid:id=" @+id/button1 "android:layout_width=" Wrap_content "Android:layout_ height= "Wrap_content" android:layout_alignparentright= "true" android:layout_alignparenttop= "true" Android:layout_ marginright= "19DP" android:layout_margintop= "36DP" android:text= "button"/></relativelayout>
Best of all, it's a matter of authority. Because of the network operation, so you can not forget to add Internet permissions, look at Androidmainfest.xml
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.example.androidupload "android:versioncode=" 1 "android:versionname=" 1.0 ">< uses-sdkandroid:minsdkversion= "8" android:targetsdkversion= "/><uses-permission android:name=" Android.permission.INTERNET "/><applicationandroid:allowbackup=" true "android:icon=" @drawable/ic_launcher " Android:label= "@string/app_name" android:theme= "@style/apptheme" ><activityandroid:name= " Com.example.androidupload.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></application></manifest>
In this way, you can use your phone to upload images to the server.

Android simple implementation to upload phone pictures to the server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.