First, the client code, "write only the main code here."
Let's get a first one.
Iv_photo.setonclicklistener (New onclicklistener () {@Overridepublic void onclick (View V) {new actionsheetdialog (sendgoodsdetailsactivity.this). Builder (). Settitle ("Upload vehicle photos"). Setcancelable ( False). Setcanceledontouchoutside (False). Addsheetitem ("Photo Upload", sheetitemcolor.blue, new Onsheetitemclicklistener () {@Overridepublic void onclick (Int which) {// Photo// Sets the save path of the picture as the global variable Imagefilepath = environment.getexternalstoragedirectory (). GetAbsolutePath () + "/ Filename.jpg "; File temp = new file (Imagefilepath); Uri imagefileuri = uri.fromfile (temp); /Get the file Uri intent it = new intent (mediastore.action_image_capture);// Jump to Camera Activityit.putextra (Android.provider.mediastore.extra_output, imagefileuri);//Tell the camera to finish shooting the output image to the specified URI startactivityforresult (it, 102);}}). Addsheetitem ("album Selection", sheetitemcolor.blue, new onsheetitemclicklistener () {@OveRridepublic void onclick (Int which) {// album selection intent intent1 = new Intent (intent.action_get_content); Intent1.setdataandtype (mediastore.images.media.external_content_uri, " image/* "); Startactivityforresult (intent1, 103);}}). Show ();}});
@Overridepublic void onactivityresult (int requestcode, int resultcode, intent data) {switch (Requestcode) { case 102: if (resultcode == ACTIVITY.RESULT_OK) { bitmap bmp = bitmapfactory.decodefile (ImageFilePath); iv _photo.setimagebitmap (BMP); } break; case 103: bitmap bm = null; External Program Access ContentProvider provides data can be accessed via Contentresolver interface ContentResolver resolver = Getcontentresolver (); try {uri originaluri = data.getdata (); // get the uribm of the picture = mediastore.images.media.getbitmap (Resolver, originaluri); // appears to bitmap pictures// Here begins the second part, gets the path of the picture:string[] proj = { mediastore.images.media.data };// Seems to be an Android Multimedia database package interface, specific look at the Android document @suppresSwarnings ("deprecation") Cursor cursor = managedquery (originaluri, proj, null, Null, null);// According to my own understanding This is the index value of the image to get the user's choice int column_index = Cursor.getcolumnindexorthrow (MediaStore.Images.Media.DATA);// move the cursor to the beginning Careless is prone to cross-border Cursor.movetofirst ();// finally gets the picture path based on the index value string path = cursor.getstring (column_index ); Iv_photo.setimageuri (Originaluri); } catch (ioexception e) {e.printstacktrace (); } break; }super.onactivityresult (requestcode,resultcode,data);}
Below is a tool class for uploading, hehe, from the Internet to find a great God, you can use
/** * * Uploading tools * @author spring sky * Email:[email Protected] * qq:840950105 * myname: Shi Ming */public class uploadutil { private static final String TAG = "UploadFile"; private static final int TIME_OUT = 10*1000; Timeout period private static final String CHARSET = "Utf-8"; //setting encoding /** * android uploading files to server * @param file files to upload * @param requesturl requested rul * @return return the contents of the response */ public static string uploadfile (File file,String requesturl) {   &Nbsp; string result = null; string boundary = uuid.randomuuid (). toString (); //Border 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); &Nbsp; conn.setconnecttimeout (time_out); conn.setdoinput (TRUE); //allow input stream conn.setdooutput (TRUE); //allow output stream conn.setusecaches (false); //is not allowed to use cache conn.setrequestmethod ("POST"); //Request method conn.setrequestproperty ("Charset", charset); //Set Code Conn.setrequestproperty ("Connection", "keep-alive"); conn.setrequestproperty ("Content-type", CONTENT_TYPE + "; boundary=" + boundary); conn.connect (); if (file!=null) { /** * when the file is not empty, package and upload the file */ dataoutputstream dos = new dataoutputstream ( Conn.getoutputstream ()); stringbuffer sb = new stringbuffer (); &nbSp; sb.append (PREFIX); sb.append (boundary); sb.append (line_end); /** * here the key note: * name inside the value for the server side need key only this key To get the corresponding file * filename is the name of the file, including 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 is = new fileinputstream (file); byte[] bytes = new byte[ 1024]; int len = 0; while ((Len=is.read ( bytes)!=-1) { dos.write (Bytes, 0, len); } is.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, get the flow of the response */ int res = conn.getresponsecode (); if (res==200) { inputstream input = conn.getinputstrEAM (); stringbuffer sb1= new stringbuffer (); int ss ; while ((Ss=input.read ())!=-1) { sb1.append ((char) SS); } result = sb1.tostring (); system.out.println (Result); } } } catch (malformedurlexception e) { e.printstacktrace (); } catch (ioexception e) { e.printstacktrace (); } return result; }}
The next is the way to call the upload, I picked it out here.
File File = new file (path); The path here is the global variable for that address, string result = Uploadutil.uploadfile (file, Requesturl);
Here the client is done, here is the server code, here I use the servlet
Public class uploadshipservlet extends httpservlet {private static final long serialversionuid = 1l;private string path;public uploadshipservlet () {super ();} Public void doget (httpservletrequest request, httpservletresponse response) Throws servletexception, ioexception {this.dopost (request, response);} Protected void dopost (Httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {response.setcontenttype ("Text/html;charset=utf-8"); Request.setcharacterencoding ("Utf-8"); Response.setcharacterencoding ("Utf-8"); Printwriter out = response.getwriter ();// Creating a File Project Factory object diskfileitemfactory factory = new diskfileitemfactory ();// set File upload path String upload = this.getservletcontext (). Getrealpath ("/");// gets the default temporary file save path for the system, which is the Temp folder under the Tomcat root directory StriNg temp = system.getproperty ("Java.io.tmpdir");// set buffer size to 5mfactory.setsizethreshold (1024 * 1024 * 5);// Set Temp folder to Tempfactory.setrepository (New file (temp));// Use factory instantiation Upload component,servletfileupload to parse file upload request servletfileupload servletfileupload = new Servletfileupload (Factory);// parsing results are placed in list try {list<fileitem> list = Servletfileupload.parserequest (Request);for (fileitem item : list) {String name = item.getfieldname (); Inputstream is = item.getinputstream ();if (Name.contains ( "Content")) {system.out.println (Inputstream2string (IS));} else if (Name.contains ("img")) {try {path = upload+ "\ \" +item.getname (); Inputstream2file (Is, path); break;} catch (exception e) {e.printstacktrace ();}} Out.write (path); //Here I put the server successfully, returned to the client after the successful upload path} catch (Fileuploadexception e) {e.printstacktrace (); SYSTEM.OUT.PRINTLN ("failure"); Out.write ("failure");} Out.flush (); Out.close ();} Stream into string public static string inputstream2string (Inputstream is) throws Ioexception {bytearrayoutputstream baos = new bytearrayoutputstream (); int i = -1;while ((I = is.read ()) != -1) {baos.write (i);} Return baos.tostring ();} Stream into file Public static void inputstream2file (inputstream is, string Savepath) throws exception {system.out.println ("File Save path:" + savepath); File file = new file (Savepath);inputstream inputsteam = is; Bufferedinputstream fis = new bufferedinputstream (Inputsteam); Fileoutputstream fos = new fileoutputstream (file);int f;while (f = Fis.read ()) != -1) {fos.write (f);} Fos.flush (); fOs.close (); Fis.close (); Inputsteam.close ();}}
OK, so it's done, more after finishing good useful.
Android photo get photo path and upload to server +servlet code