There are many situations in Android development that require uploading images to the server, such as uploading avatars, for example, to develop an app. This article gives a brief analysis of how to upload avatar images from Android terminal.
Upload Tool class:
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.uuid;/** * * Upload Tool class * */public class Uploadutils {private static final String TAG = "Upload ";p rivate static final int time_out = 1000 * 1000; Timeout time private static final String CHARSET = "Utf-8"; Set Encoding/** * Android upload file to server * * @param file * need to upload files * @param requesturl * Request Rul * @return Return the response Content */public static string uploadfile (file file, string requesturl) {string result = NULL; String boundary = Uuid.randomuuid (). toString (); The boundary identifier randomly generates a 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 inputStream Conn.setdooutput (true); Allow output stream conn.setusecaches (false); Cache Conn.setrequestmethod ("POST") is not allowed; Request Mode Conn.setrequestproperty ("Charset", Charset); Set the encoding Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("Content-type", Content_Type + " ; boundary= "+ boundary); {/** * When the file is not empty, wrap the file and upload */dataoutputstream dos = new DataOutputStream (conn.getout Putstream ()); StringBuffer sb = new StringBuffer (), Sb.append (PREFIX); sb.append (boundary); Sb.append (line_end);/** * Focus here: The value inside the 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, such as: Abc.png */sb.append ("Content-disposition:form-data; Name=\ "upload\"; Filename=\ "" + file.getname () + "\" "+ line_end); Sb.append (" Content-type:application/octet-stream; Charset= "+ charset + line_end); Sb.append (line_end);d Os.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 ();d Os.writE (Line_end.getbytes ()); byte[] End_data = (PREFIX + boundary + PREFIX + line_end). GetBytes ();d os.write (end_data); Dos.flush ();/** * Gets the response code 200 = Success When the response is successful, gets the stream 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),//if (res==200)//{//}//else{//log.e (TAG, "request Error"),//}}} catch ( Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} return result;}}
Image upload Package class:
Import Java.io.file;import Android.os.environment;public class Tuploadfile {private static Tuploadfile Mtuploadfile = Null;private Tuploadfile () {}public synchronized static tuploadfile getinstance () {if (mtuploadfile = = null) mtuploadfile = new Tuploadfile (); return mtuploadfile;} public string Tuploadheadimage (string cusid) {//user ID number, upload avatar, one user corresponding to an avatar String result = ""; For example, it is saved locally named Myphoto.png after being cropped and then uploaded locally to the server result = Uploadutils.uploadfile (The new File Environment.getexternalstoragedirectory (). GetAbsolutePath () + "/myphoto.png"), "Server domain name" + cusid); return result;}
The application class that holds global variables in app apps:
public class TestApplication extends application {private static testapplication minstance = Null;public static Tuploadfil E mtuploadfile;//A unique testapplication instance in singleton mode public static TestApplication getinstance () {if (null = = Minstance) Minstance = new TestApplication (); return minstance;} public void OnCreate () {super.oncreate (); Mtuploadfile = Tuploadfile.getinstance ();}}
An asynchronous way to upload avatar images:
public class Asyncheaduptask extends Asynctask<string, Integer, string> {//upload avatar protected String doinbackground ( String ... params) {String code = ""; try {string result = TestApplication.mTUploadFile.TUploadHeadImage (params[0]);// The parameters are user idjsonobject ResultCode = new Jsonobject (result), code = resultcode.getstring ("Commonack");//server-side return verification Code} catch ( Exception e) {e.printstacktrace ();} return code;} protected void OnPostExecute (String result) {Stopprogressdialog ();//Stop delay animation after successful upload if (Result.equals ("111111")) {// The server returned a verification code of 111111 to upload the avatar successfully toast.maketext (getactivity (), "Upload avatar Success", Toast.length_short). Show (); else {Toast.maketext (getactivity (), "Network connection Error", Toast.length_short). Show (); }} protected void OnPreExecute () {super.onpreexecute (); Startupprogressdialog ();//upload delay animation }}
In the main acitivty file, it is possible to upload the avatar to the server by invoking the above method of uploading the avatar image asynchronously.
Uploading images to the server in Android