This is the main function package com.zmb.updemo;import java.io.bufferedreader;import java.io.dataoutputstream; import java.io.file;import java.io.fileinputstream;import java.io.inputstream;import java.io.inputstreamreader;import java.io.outputstream;import java.net.httpurlconnection;import java.net.malformedurlexception;import java.net.url;import java.util.uuid;import org.apache.http.httpresponse;import org.apache.http.client.httpclient;import org.apache.http.client.methods.httpget;import org.apache.http.impl.client.defaulthttpclient;import Android.app.activity;import android.app.alertdialog;import android.content.contentresolver;import android.content.intent;import android.database.cursor;import android.graphics.bitmap;import android.graphics.BitmapFactory;import android.net.Uri;import android.os.AsyncTask;import android.os.bundle;import android.provider.mediastore;import android.util.log;import android.view.menu;import android.view.view;import android.view.view.onclicklistener;import android.widget.button;import android.widget.imageview; Import android.widget.progressbar;import android.widget.textview;public class mainactivity extends activity implements onclicklistener{ private button mbtnupload, Whether; private progressbar mpgbar; private textview mtvprogress; private Button choose; private ImageView imageView; private File file; private uploadtask uploadtask; private static final int time_out = 120*10000000; //Timeout period private static final String CHARSET = "Utf-8"; //set Encoding private static final string requesturl= "http:// 192.168.0.164:9580/ekp/testservlet "; private  alertdialog dialog; @Override protected void oncreate (bundle savedinstancestate) { super.oncreate (savedinstancestate); setcontentview (R.layout.activity_main); mBtnUpload = (Button) Findviewbyid (r.id.uploadimage); choose = ( Button) Findviewbyid (r.id.selectimage), imageview= (ImageView) findviewbyid (R.id.imageview); mbtnupload.setonclicklistener (This), choose.setonclicklistener (this); View upview = getlayoutinflater (). Inflate (r.layout.progress_bar_item, null); mPgBar = (ProgressBar) Upview.findviewbyid (r.id.pb_filebrowser_uploading); mtvprogress = (TextView) Upview.findviewbyid (r.id.tv_filebrowser_uploading); whether = (Button) Upview.findviewbyid (R.id.upload_over); whether.setonclicklistener (this); dialog=new alertdialog.builder (MainActivity.this). Setview (Upview). Create (); } private class uploadtask extends asynctask<void, integer, string>{ @Override protected void OnPostExecute (String result) { mtvprogress.settext (Result); Whether.settext ("OK"); } @Override protected void onpreexecute () { dialog.show (); mtvprogress.settext ("Uploading pictures ..."); Whether.settext ("Cancel"); } @Override protected void onprogressupdate ( Integer... values) { Integer num=values[0]; Mpgbar.setprogress (num); mtvprogress.settext ("Uploading pictures ..." + num + "%"); } @Override protected string doinbackground (void...parem) { string boundary&Nbsp;= uuid.randomuuid (). toString (); //boundary identification random generation string prefix = "--" , LINE_END = "\ r \ n"; string CONTENT_TYPE = "Multipart/form-data"; //content Type try { url url = new url (RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openconnection (); conn.setreadtimeout (time_out); conn.setconnecttimeout (TIME_OUT); conn.setdoinput (TRUE); //allow input stream conn.setdooutput (true); // Allow output stream conn.setusecaches (false); //does not allow caching Conn.setrequestmethod ("POST"), //request mode conn.setrequestproperty ("Charset", charset); //set encoding &Nbsp; conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("Content-type", content_type + "; boundary=" + BOUNDARY); if (file!=null) { /** * when the file is not empty, package and upload the file */ outputstream outputsteam=conn.getoutputstream (); dataoutputstream dos = new dataoutputstream (OutputSteam); stringbuffer sb = new stringbuffer (); Sb.append (PREFIX); sb.append (boundary); sb.append ( Line_end); /** * Here the key note: * name.The value of the polygon is server-side required key only this key can get the corresponding file * FileName is the name of the file and contains the suffix such as:abc.png */ sb.append ("content-disposition: form-data; Name=\ "img\"; filename=\ "" +file.getname () + "\" "+line_end); sb.append (" content-type: application/octet-stream; charset= "+charset+line_end); Sb.append (Line_end); dos.write (Sb.tostring (). GetBytes ()); Inputstream fis = new fileinputstream (file); long total = fis.available (); string totalstr = string.valueof (total); &NBSP;&NBSP;&NBSP;LOG.D ("File Size", &NBSP;TOTALSTR); byte[] buffer = new byte[8192]; // 8k int count = 0; int length = 0; while ((count = fis.read (buffer)) != -1) { dos.write (Buffer, 0, count); length += count; publishprogress ((int) (length / (float) total) * 100); //to demonstrate progress, hibernate 50 Ms thread.sleep (; ) } fis.close (); dos.write (LINE_ End.getbytes ()); byte[] end_data = (prefix+boundary+prefix+line_end). GetBytes (); dos.write (End_data); dos.flush (); /** * Get Response code 200= Success * When the response succeeds, gets the stream of the response &nbsP; */ int res = conn.getresponsecode (); if (res==200) { return "Upload succeeded!"; } } } catch (malformedurlexception e) { e.printstacktrace (); } catch (exception e) { e.printstacktrace (); } return "Upload failed!"; }} @Override public boolean oncreateoptionsmenu (menu menu) { // inflate the menu; this adds items to the action bar if it is present. getmenuinflater (). Inflate (R.menu.main, menu); return true; } @Override public void onclick (view v) { int id=v.getid (); switch&nBSP; (ID) { case R.id.selectImage: /*** * This is called Android built-in intent, to filter the image file  , but also can filter other */ intent intent = new intent (); intent.settype ("image/*"); intent.setaction (intent.action_get_content); //callback Image class use Startactivityforresult (intent, result_canceled); break; case r.id.upload _over: if ("OK". Equals (Whether.gettext () + "")) { dialog.dismiss (); }else{ uploadtask.cancel (True); dialog.dismiss (); } break; default: /* //View here is the frame for uploading progress Example of //asynctask uploadtask=new uploadtask (); Uploadtask.execute (); */ httpClient client = new defaulthttpclient (); httpget get = new httpget ("Http://192.168.0.164:9580/ekp/TestServlet"); try { httpresponse response = client.execute (GET); BufferedReader reader = new bufferedreader (New inputstreamreader ( response.getentity (). GetContent ())); for ( String s = reader.readline (); s != null; s = reader.readline ()) { &Nbsp; system.out.println ("------------- -----??????"); } } catch (exception e) { e.printstacktrace (); } break; } } /** * callback method of execution */ @SuppressWarnings ("deprecation") @Override protected void onactivityresult ( Int requestcode, int resultcode, intent data) { if (resultCode== ACTIVITY.RESULT_OK) { /** * When the selected picture is not empty, the way to get to the picture */ uri uri = data.getdata (); try&nbSp { string[] pojo = {mediastore.images.media.data}; cursor cursor = managedquery (uri, pojo, null, null , null); if (Cursor!=null) { Contentresolver cr = this.getcontentresolver (); int colunm_ Index = cursor.getcolumnindexorthrow (MediaStore.Images.Media.DATA); Cursor.movetofirst (); string path = cursor.getstring (Colunm_index) ; /*** * here to add such a judgment is mainly for the third party software selection, For example: Using a third-party file Manager, you choose the file is not necessarily a picture, so that we judge the file suffix * if it is a picture format, then you can */ if (Path.endsWith ("jpg") | | Path.endswith ("PNG")) { file=new file (Path); bitmap bitmap = bitmapfactory.decodestream (Cr.openinputstream (URI)); imageview.setimagebitmap (bitmap); } } } catch (exception e) { E.printstacktrace (); } } /** * callback using */ super.onactivityresult (requestcode, resultcode, data); } }
Master configuration file
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http// Schemas.android.com/apk/res/android " android:orientation=" vertical " android:layout_width= "Fill_parent" android:layout_height= "Fill_parent" > <button android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:text= " Select Picture " android:id=" @+id/selectimage " /> <button android:layout_width= "Fill_parent" android:layout_height= "wrap_content" android:text= "Upload image" android:id= "@+id/uploadimage" /> <imageview andrOid:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:id= "@+id/imageview" /></LinearLayout>
There is a configuration file for the progress bar
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http// Schemas.android.com/apk/res/android " android:layout_width=" Match_parent " android:layout_height= "Wrap_content" android:paddingbottom= "@dimen/activity _vertical_margin " android:paddingleft=" @dimen/activity_horizontal_margin " android:paddingright= "@dimen/activity_horizontal_margin" android:paddingtop = "@dimen/activity_vertical_margin" android:orientation= "vertical" > <progressbar android:id= "@+id/pb_filebrowser_uploading" style= "? Android:attr/progressbarstylehorizontal" android:layout _width= "Match_parent" android:layout_height= "Wrap_content"/> <textview anDroid:id= "@+id/tv_filebrowser_uploading" android:layout_width= "Match_parent" android:layout_height= "Wrap_content"/> <button android:id= "@+id/upload_over" android:layout_width= "Match_parent" android:layout_height= "Wrap_content"/></linearlayout>