A simple Android + Servlet Image Upload example: Android servlet
The example is relatively simple. The server is a Java Web Servlet. In the doPost method, the image is received and saved, and the saved image name is returned to the client. The key code is as follows:
@ SuppressWarnings ("deprecation") public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); // set the encoding // Get disk file entries factory DiskFileItemFactory factory = new DiskFileItemFactory (); // obtain the path to which the file needs to be uploaded String path = request. getRealPath ("/upload"); File file = new File (path); if (! File. exists () {file. mkdirs ();} factory. setRepository (new File (path); // set the cache size factory. setSizeThreshold (1024*1024); // File upload processing ServletFileUpload upload = new ServletFileUpload (factory ); try {// you can upload multiple file lists <FileItem> List = (list <FileItem>) upload. parseRequest (request); for (FileItem item: list) {// obtain the attribute name String name = item. getFieldName (); // if the obtained form information is normal text information if (item. isFormField () {// obtain the String entered by the user, because the form is submitted to String-type String value = item. getString (); request. setAttribute (name, value);} else {// obtain the path String value = item. getName (); // index to the last backslash int start = value. lastIndexOf ("\"); // intercept the name of the uploaded file. Add 1 to remove the backslash, String filename = value. substring (start + 1); request. setAttribute (name, filename); // write it to the disk item. write (new File (path, filename); // a third-party System. out. println ("uploaded successfully:" + filename); response. getWriter (). print (filename); // return the path to the client} catch (Exception e) {System. out. println ("Upload Failed"); response. getWriter (). print ("Upload Failed:" + e. getMessage ());}}
This method is also suitable for uploading web images.
Key client code:
/*** File Upload ** @ param urlStr interface path * @ param filePath local image path * @ return */public static String formUpload (String urlStr, String filePath) {String rsp = ""; HttpURLConnection conn = null; String BOUNDARY = "|"; // try {URL url = new URL (urlStr ); conn = (HttpURLConnection) url. openConnection (); conn. setConnectTimeout (5000); conn. setreadtimeouts (30000); conn. setDoOutput (true); conn. setDoInput (t Rue); 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 fi Lename = 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 + "\" \ r \ n "); strBuf. append ("Content-Type:" + contentType + "\ r \ n"); out. write (strBuf. toString (). getBytes (); DataInputStream in = new DataInputStream (new FileInputStream (file); int bytes = 0; byte [] bufferOut = new Te [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 the returned 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 ;}
Server legend:
Client legend:
Note: during the test, write the complete local area network IP address on the client:
/*** Image Upload path */public static final String UPLOAD_URL = "http: // 192.168.1.188: 8080/uploadImage/UploadServlet "; /*** image download path */public static final String DOWNLOAD_URL = "http: // 192.168.1.188: 8080/uploadImage/upload /";
Source Code address: http://download.csdn.net/detail/baiyuliang2013/8714775