The example is simple, the server is the Java Web Servlet,dopost method to receive pictures and save, and then return the saved picture name to the client, the key code:
@SuppressWarnings ("deprecation") public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {request.setcharacterencoding ("utf-8"); Set encode//Get Disk File entry Factory Diskfileitemfactory factory = new Diskfileitemfactory (); Gets the path that the file needs to be uploaded to String path = Request.getrealpath ("/upload"); File File=new file (path); if (!file.exists ()) {file.mkdirs (); } factory.setrepository (new File path); Sets the size of the cache Factory.setsizethreshold (1024*1024); File upload processing servletfileupload upload = new Servletfileupload (factory); try {//can upload multiple files list<fileitem> List = (list<fileitem>) upload.parserequest (request); for (Fileitem item:list) {//Gets the property name String name = Item.getfieldname (); If the obtained form information is plain text information if (Item.isformfield ()) { Gets the user-specific input string, because the form submits a string of type value = Item.getstring (); Request.setattribute (name, value); }else{//Gets the path name String value = Item.getname (); Index to the last backslash int start = value.lastindexof ("\ \"); Intercept the string name of the uploaded file, plus 1 to remove the backslash, string filename = value.substring (start+1); Request.setattribute (name, filename); Write to Disk item.write (path,filename);//SYSTEM.OUT.PRINTLN provided by the third party ("Upload succeeded: "+filename); Response.getwriter (). Print (filename),//return path to the client}}} catch (Exception e) {System.out.println ("Upload failed"); Response.getwriter (). Print ("Upload failed:" +e.getmessage ()); } }
This method is also applicable to Web-page image upload, not the focus of this article, not explained.
Client-side Key code:
/** * File Upload * * @param urlstr interface path * @param filePath local picture path * @return */public static string Formupload (String urlstr, Str ing FilePath) {String RSP = ""; HttpURLConnection conn = null; String boundary = "|"; Request header and upload file content delimiter try {URL url = new URL (URLSTR); conn = (httpurlconnection) url.openconnection (); Conn.setconnecttimeout, Conn.setreadtimeout (30000); Conn.setdooutput (true); Conn.setdoinput (true); Conn.setusecaches (false); Conn.setrequestmethod ("POST"), Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("User-agent", "mozilla/5.0" (Windows; U Windows NT 6.1; ZH-CN; rv:1.9.2.6) Conn.setrequestproperty ("Content-type", "multipart/form-data; boundary=" + boundary); OutputStream out = New DataOutputStream (Conn.getoutputstream ()); File File = new file (FilePath); String filename = File.getname (); String ContentType = "", if (Filename.endswith (". png")) {ContentType = "image/png";} if (Filename.endswith (". jpg")) {ContentType = "image/jpg";} if (Filename.endswith (". gif")) {ContentType = "Image/gif";} if (Filename.endswith (". bmp")) {ContentType = "image/bmp";} if (ContentType = = NULL | | contenttype.equals ("")) {ContentType = "Application/octet-stream";} StringBuffer strbuf = new StringBuffer () strbuf.append ("\ r \ n"). Append ("--"). Append (Boundary). Append ("\ r \ n"); Strbuf.append ("Content-disposition:form-data; Name=\ "" + filepath+ "\"; Filename=\ "+ filename +" \ "\" \ \ "\ \ \") Strbuf.append ("Content-type:" + contentType + "\r\n\r\n"); Out.write ( Strbuf.tostring (). GetBytes ());D atainputstream in = new DataInputStream (new FileInputStream (file)); int bytes = 0;byte[] Bufferout = new Byte[1024];while ((bytes = In.read (bufferout))! =-1) {out.write (bufferout, 0, bytes);} In.close (); byte[] Enddata = ("\r\n--" + boundary + "--\r\n"). GetBytes (); Out.write (Enddata); Out.flush (); Out.close ();// Read return data StringBuffer buffer = new StringBuffer (); BufferedReader reader = new BufferedReader (New InputStreamReader (Conn.getinputstream (), "Utf-8")); String line = null;while (line = Reader.readline ()) = null) {Buffer.append (line). append ("\ n");} RSP = Buffer.tostring (); Reader.close (); reader = null;} catch (Exception e) {e.printstacktrace ();} finally {if (conn! = null) {conn.disconnect (); conn = null;}} return RSP;}
Service-side legend:
Client legend:
Note: When testing, please write the full native LAN IP address on the client:
/** * Image upload path */public static final String upload_url= "Http://192.168.1.188:8080/uploadImage/UploadServlet";/** * Picture Download path */public static final String download_url= "http://192.168.1.188:8080/uploadImage/upload/";
Source Address: http://download.csdn.net/detail/baiyuliang2013/8714775
An example of a simple Android +servlet image upload