in the 9ria forum see, haven't tested, first mark to share with you. Recently, to get a project, you need to upload a photo album and photos, not negative, finally finished! However, it is necessary to explain, in fact, many of the online pictures of the tutorial, are thumbnails are not very clear, so you need to call the camera, in advance to generate an address, to identify the image of the picture Uri Specific upload code: |
Package Com.spring.sky.image.upload;import Java.util.hashmap;import Java.util.map;import android.app.Activity; Import Android.app.progressdialog;import Android.content.intent;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.bundle;import Android.os.handler;import android.os.Message; Import Android.util.log;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;import Android.widget.toast;import Com.spring.sky.image.upload.network.uploadutil;import com.spring.sky.image.upload.network.uploadutil.onuploadprocesslistener;/*** Description: Mainly used to select files and upload file operations */public class Mainactivity extends Activity implements onclicklistener,onuploadprocesslistener{private static final String TAG = " Uploadimage ";/*** to upload a file */protected static final int to_upload_file = 1; /*** upload file response */protected static final int upload_file_done = 2; Select File */pubLIC static final int to_select_photo = 3;/*** upload initialization */private static final int upload_init_process = 4;/*** upload in */private St atic final int upload_in_process = 5;/**** This URL here is my server's Java EE environment url*/private static String Requesturl = "http://192.168. 10.160:8080/fileupload/p/file!upload ";p rivate button selectbutton,uploadbutton;private ImageView imageView;private TextView uploadimageresult;private ProgressBar progressbar;private String picpath = null;private ProgressDialog progressdialog;/** called when the activity is first created. */@Overridepublic void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.main); Initview ();} /*** initialization Data */private void Initview () {Selectbutton = (button) This.findviewbyid (r.id.selectimage); Uploadbutton = (Button ) This.findviewbyid (r.id.uploadimage); Selectbutton.setonclicklistener (this); Uploadbutton.setonclicklistener ( this); ImageView = (ImageView) This.findviewbyid (r.id.imageview); uploadimageresult = (TextView) findviewbYid (r.id.uploadimageresult);p rogressdialog = new ProgressDialog (this);p Rogressbar = (progressBar) Findviewbyid ( R.ID.PROGRESSBAR1);} @Overridepublic void OnClick (View v) {switch (V.getid ()) {case R.id.selectimage:intent Intent = new Intent (this,selectpic Activity.class); Startactivityforresult (Intent, To_select_photo); Break;case r.id.uploadimage:if (PicPath!=null) { Handler.sendemptymessage (to_upload_file);} Else{toast.maketext (This, "Error uploading file path", Toast.length_long). Show (); Break;default:break;}} @Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {if (Resultcode==activity.result _OK && Requestcode = = To_select_photo) {Picpath = Data.getstringextra (Selectpicactivity.key_photo_path); LOG.I (TAG, "final Selected picture =" +picpath); Bitmap BM = bitmapfactory.decodefile (Picpath); Imageview.setimagebitmap (BM);} Super.onactivityresult (Requestcode, ResultCode, data);} /*** Upload Server Response callback */@Overridepublic void onuploaddone (int responsecode, String message) {Progressdialog.dismiss (); Message msg = Message.obtain (); msg.what = Upload_file_done;msg.arg1 = Responsecode;msg.obj = Message;handler.sendmessage (msg);} private void Touploadfile () {Uploadimageresult.settext ("uploading ...");p rogressdialog.setmessage ("Uploading Files ..."); Progressdialog.show (); String Filekey = "pic"; Uploadutil uploadutil = Uploadutil.getinstance (); Uploadutil.setonuploadprocesslistener (this); Set listener listening upload status map<string, string> params = new hashmap<string, string> ();p arams.put ("OrderId", "11111"); Uploadutil.uploadfile (Picpath,filekey, requesturl,params);} Private Handler Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {switch (msg.what) {case To_upload _file:touploadfile (); break;case UPLOAD_INIT_PROCESS:progressBar.setMax (MSG.ARG1); Break;case upload_in_process: Progressbar.setprogress (MSG.ARG1); Break;case upload_file_done:string result = "Response code:" +msg.arg1+ "\ n Response message:" +msg.obj+ "\ N Time-consuming: "+uploadutil.getrequesttime () +" seconds "; Uploadimageresult.settext (result); break;default:break;} Super.handlemessage (MSG);}}; @Overridepublic void onuploadprocess (int uploadsize) {Message msg = Message.obtain (); msg.what = upload_in_process; MSG.ARG1 = Uploadsize;handler.sendmessage (msg);} @Overridepublic void initupload (int fileSize) {Message msg = Message.obtain (); msg.what = Upload_init_process;msg.arg1 = f Ilesize;handler.sendmessage (msg);}}
2. Choose the image interface, mainly related to two ways: select pictures and timely photo pictures
Package Com.spring.sky.image.upload;import Android.app.activity;import Android.content.contentvalues;import Android.content.intent;import Android.database.cursor;import Android.net.uri;import Android.os.Bundle;import Android.os.environment;import Android.provider.mediastore;import Android.util.log;import android.view.MotionEvent ; Import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.linearlayout;import android.widget.toast;/*** @author Spring sky<br>* Description: Primarily used to select file operations */public Class Selectpicactivity extends Activity implements onclicklistener{/**** take pictures with camera get picture */public static final int select_ Pic_by_tack_photo = 1;/**** use picture in album */public static final int select_pic_by_pick_photo = 2;/**** Get picture path intent from key*/ public static final String key_photo_path = "Photo_path";p rivate static final String TAG = "Selectpicactivity";p rivate Lin Earlayout dialoglayout;private Button takephotobtn,pickphotobtn,cancelbtn;/** gets to the picture path */private String picpath;private Intent lastintent;p rivate Uri photouri; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.select_pic_layout); Initview ();} /*** initialization load view*/private void Initview () {dialoglayout = (linearlayout) Findviewbyid (r.id.dialog_layout); Dialoglayout.setonclicklistener (this); takephotobtn = (Button) Findviewbyid (R.id.btn_take_photo); Takephotobtn.setonclicklistener (This);p ickphotobtn = (Button) Findviewbyid (R.id.btn_pick_photo); Pickphotobtn.setonclicklistener (this); cancelbtn = (Button) Findviewbyid (r.id.btn_cancel); Cancelbtn.setonclicklistener (this); lastintent = Getintent ();} @Overridepublic void OnClick (View v) {switch (V.getid ()) {case r.id.dialog_layout:finish (); Break;case R.id.btn_take_ Photo:takephoto (); break;case R.id.btn_pick_photo:pickphoto (); Break;default:finish (); break;}} /*** take pictures get picture */private void Takephoto () {//before performing a photo shoot, you should first determine if the SD card exists string sdstate = Environment.getexternalstoragestate (); if ( Sdstate.equals (ENVIronment. media_mounted) {Intent Intent = new Intent (mediastore.action_image_capture);//"Android.media.action.IMAGE_CAPTURE" /**** need to explain, the following operation using a camera to take pictures, pictures will be stored in the photo album * Here is a good thing to do is to get the picture is the original image after the photo * If not practical contentvalues to store the photo path, photos after the picture for the thumbnail is not clear */contentvalues values = new Contentvalues (); Photouri = This.getcontentresolver (). Insert (MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); Intent.putextra (Android.provider.MediaStore.EXTRA_OUTPUT, Photouri);/**-----------------* * Startactivityforresult (Intent, Select_pic_by_tack_photo);} Else{toast.maketext (This, "memory card does not exist", Toast.length_long). Show ();}} /**** take the picture from the album */private Void Pickphoto () {Intent Intent = new Intent (); Intent.settype ("image/*"); Intent.setaction ( intent.action_get_content); Startactivityforresult (Intent, Select_pic_by_pick_photo);} @Overridepublic boolean ontouchevent (Motionevent event) {finish (); return super.ontouchevent (event);} @Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {if (ResultCode = = Activity. RESULT_OK) {Dophoto (requestcode,data);} Super.onactivityresult (Requestcode, ResultCode, data);} /*** after selecting the picture, get the path of the picture * @param requestcode* @param data*/private void dophoto (int requestcode,intent data) {if (Requestcode = = Select_pic_by_pick_photo)//from the album to take pictures, some phones have unusual situation, please note {if (data = null) {Toast.maketext (this, "Select Picture file Error", Toast.length_ LONG). Show (); return;} Photouri = Data.getdata (), if (Photouri = = null) {Toast.maketext (this, "Error selecting picture file", Toast.length_long). Show (); return;}} String[] Pojo = {MediaStore.Images.Media.DATA}; cursor cursor = managedquery (Photouri, Pojo, NULL, null,null); if (cursor! = NULL) {int columnindex = Cursor.getcolumnindexorthrow (pojo[0]); Cursor.movetofirst ();p Icpath = Cursor.getstring (columnindex); Cursor.close ();} LOG.I (TAG, "ImagePath =" +picpath); if (Picpath! = null && (Picpath.endswith (". png") | | Picpath.endswith (". PNG ") | | Picpath.endswith (". jpg") | | Picpath.endswith (". JPG ")) {Lastintent.putextra (Key_photo_path, Picpath); Setresult (ACTIVITY.RESULT_OK, lastintent); Finish ();} Else{toast.maketext (This, "Select picture file is incorrect", Toast.length_long). Show ();}}
3. Upload the tool class, the main implementation of the image upload, upload process initialization monitoring and upload completed monitoring, and upload time-consuming calculation
Package Com.spring.sky.image.upload.network;import Java.io.dataoutputstream;import Java.io.file;import Java.io.fileinputstream;import Java.io.ioexception;import Java.io.inputstream;import java.net.HttpURLConnection; Import Java.net.malformedurlexception;import java.net.url;import Java.util.iterator;import Java.util.Map;import Java.util.uuid;import android.util.log;/*** * Upload Tool class * Supports uploading files and parameters */public class Uploadutil {private static Uploadutil Uploadutil;private static final String boundary = Uuid.randomuuid (). toString (); The boundary identifier randomly generates a private static final string PREFIX = "--";p rivate static final string line_end = "\ r \ n";p rivate static final S Tring Content_Type = "Multipart/form-data"; Content Type Private Uploadutil () {}/*** singleton mode get Upload Tool class * @return */public static Uploadutil getinstance () {if (null = = Uploadutil) { Uploadutil = new Uploadutil ();} return uploadutil;} private static final String TAG = "Uploadutil";p rivate int readtimeout = 10 * 1000; Read timeout private int connecttimeout = 10 * 1000; Timeout Time/*How long does the request use */private static int requesttime = 0;private static final String CHARSET = "Utf-8"; Set encoding/**** upload succeeded */public static final int upload_success_code = 1;/*** file does not exist */public static final int Upload_file_not_exi Sts_code = 2;/*** Server error */public static final int upload_server_error_code = 3;protected static final int what_to_upload = 1;protected static final int what_upload_done = 2;/*** Android upload file to server * * @param filepath* The path of the file to be uploaded * @param filekey* on Web page On <input type=file name=xxx/> xxx is here filekey* @param requesturl* request url*/public void UploadFile (String filePath, String Filekey, String requesturl,map<string, string> param) {if (FilePath = = null) {SendMessage (upload_file_not_ Exists_code, "file does not exist"); return;} try {File File = new file (FilePath); UploadFile (File, Filekey, Requesturl, param);} catch (Exception e) {sendMessage (UPLOAD _file_not_exists_code, "file does not exist"); E.printstacktrace (); return;}} /*** Android upload file to server * * @param file* need to upload files * @param filekey* on the web <input type=file name=xxx/> xxx is here filekey* @param requesturl* request url*/public void UploadFile (final file file, final String filekey,final String Requesturl, Final map<string, string> param) {if (file = = NULL | | (!file.exists ())) {SendMessage (Upload_file_not_exists_code, "file does not exist"); return;} LOG.I (TAG, "requested url=" + Requesturl); LOG.I (TAG, "requested Filename=" + file.getname ()); LOG.I (TAG, "requested filekey=" + filekey); new Thread (new Runnable () {//Open thread upload file @overridepublic void run () {touploadfile (file, Filekey, Requesturl, param);}). Start ();} private void Touploadfile (file file, string Filekey, String requesturl,map<string, string> param) {string result = N Ull;requesttime= 0;long requesttime = System.currenttimemillis (); Long responsetime = 0;try {URL url = new URL (requesturl); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setreadtimeout (readtimeout); Conn.setconnecttimeout (ConnectTimeout); Conn.setdoinput (true); Allow input stream Conn.setdooutput (true); Allow output stream conn.setusecaches (false); Cache C is not allowedOnn.setrequestmethod ("POST"); Request Mode Conn.setrequestproperty ("Charset", Charset); Set the encoding Conn.setrequestproperty ("Connection", "keep-alive"), Conn.setrequestproperty ("User-agent", "mozilla/4.0" ( Compatible MSIE 6.0; Windows NT 5.1; SV1) Conn.setrequestproperty ("Content-type", Content_Type + "; boundary=" + boundary);//Conn.setrequestproperty (" Content-type "," application/x-www-form-urlencoded ");/*** when the file is not empty, wrap the file and upload */dataoutputstream dos = new DataOutputStream (Conn.getoutputstream ()); StringBuffer SB = null; String params = "";/**** the following is used to upload parameters */if (param! = null && param.size () > 0) {iterator<string> it = PARAM.K Eyset (). iterator (); while (It.hasnext ()) {sb = NULL;SB = new StringBuffer (); String key = It.next (); String value = Param.get (key), Sb.append (PREFIX). Append (Boundary). Append (Line_end); Sb.append ("Content-disposition: Form-data; Name=\ ""). Append (Key). Append ("\" "). Append (Line_end). Append (line_end) sb.append (value). Append (line_end);p arams = Sb.tostring (); LOG.I (TAG, key+ "="+params+" # # ");d Os.write (Params.getbytes ());//Dos.flush ();}} SB = Null;params = NULL;SB = new StringBuffer ();/*** here: The value in name is the server side need key only this key can get the corresponding file * filename is the name of the file, including the suffix name of the For example: Abc.png*/sb.append (PREFIX). Append (Boundary). Append (Line_end); Sb.append ("Content-disposition:form-data; Name=\ "" + filekey+ "\"; Filename=\ "" + file.getname () + "\" "+ line_end); Sb.append (" content-type:image/pjpeg "+ line_end); The Content-type configured here is important for the server-side identification of the type of file Sb.append (line_end);p arams = sb.tostring (); sb = null; LOG.I (TAG, File.getname () + "=" + params+ "# #");d Os.write (Params.getbytes ());/** upload file */inputstream is = new FileInputStream (file); Onuploadprocesslistener.initupload ((int) file.length ()); byte[] bytes = new Byte[1024];int len = 0;int Curlen = 0;while (len = is.read (bytes))! =-1) {Curlen + = len;dos.write (bytes, 0, Len); onuploadprocesslistener.onup Loadprocess (Curlen);} Is.close ();d os.write (Line_end.getbytes ()) byte[] End_data = (PREFIX + boundary + PREFIX + line_end). GetBytes (); Dos.write (End_data);d Os.flush ();///Dos.write (Tempoutputstream.tobytearray ());/*** Get response Code 200 = Success When response is successful, get response stream */int res = Conn.getresponsecode (); responsetime = System.currenttimemillis (); this.requesttime = (int) (( Responsetime-requesttime)/1000); LOG.E (Tag, "Response code:" + res), if (res = =) {LOG.E (tag, "request Success"); InputStream input = Conn.getinputstream ( ); StringBuffer sb1 = new StringBuffer (), int ss;while ((ss = Input.read ())! =-1) {sb1.append ((char) SS);} result = Sb1.tostring (); LOG.E (TAG, "Result:" + result); SendMessage (Upload_success_code, "Upload result:" + result); return;} else {LOG.E (TAG, "request Error"), SendMessage (Upload_server_error_code, "Upload failed: code=" + res); return;} catch (Malformedurlexception e) {sendMessage (Upload_server_error_code, "Upload failed: error=" + e.getmessage ()); E.printstacktrace (); return;} catch (IOException e) {sendMessage (Upload_server_error_code, "Upload failed: error=" + e.getmessage ()); E.printstacktrace (); return;}} /*** Send upload results * @param responsecode* @param responsemessage*/private void SendMessage (int responsecode,string responsemessage) {onuploadprocesslistener.onuploaddone (ResponseCode, ResponseMessage );} /*** Below is a custom callback function that uses the callback upload file to complete * * @author shimingzheng* */public static interface Onuploadprocesslistener {/*** upload response * @p Aram responsecode* @param message*/void onuploaddone (int responsecode, String message);/*** upload * @param uploadsize*/void onuploadprocess (int uploadsize);/*** ready to upload * @param filesize*/void initupload (int fileSize);} Private Onuploadprocesslistener onuploadprocesslistener;public void Setonuploadprocesslistener ( Onuploadprocesslistener onuploadprocesslistener) {this.onuploadprocesslistener = Onuploadprocesslistener;} public int getreadtimeout () {return readtimeout;} public void setreadtimeout (int readtimeout) {this.readtimeout = ReadTimeout;} public int getconnecttimeout () {return connecttimeout;} public void setconnecttimeout (int connecttimeout) {this.connecttimeout = ConnectTimeout;} /*** Get upload time used * @return */public static int getrequesttime () {return requesttime;}public static Interface Uploadprocesslistener{}}
Android Select pictures or photos to upload to the server (including upload parameters)