One: the principle of realization
Recently in the Android client application development, involving the image uploaded to the backend server, I chose to do Spring3 MVC HTTP API as a background upload interface, Android Client I choose to use HttpURLConnection to submit file data through the form to upload the function, I would like to search the Internet copy to change the code is good, found no ready-made examples, Most of the examples are based on httpclient or based on BASE64 encoding later as a string to transmit image data, so I have to do it myself, refer to some information on the Internet, the final implementation based on HttpURLConnection upload files of the Android client code, Less nonsense, in fact, based on httpurlconnection implementation of file upload the most important thing is to familiarize yourself with the HTTP protocol knowledge, know the MIME file block in the HTTP protocol format representation, the basic transmission data format is as follows:
Where boundary represents the boundary of the form, as long as the content byte number is written to the HttpURLConnection object output stream in the format, the server-side spring Controller automatically responds to the acceptance, following the upload file on the browser page.
Server-Side HTTP APIs, I am based on the SPRING3 MVC implementation of the controller, the code is as follows:
@RequestMapping (value = "/uploadmyimage/{token}", method = requestmethod.post) public @ResponseBody String Getuploadfil E (httpservletrequest request, httpservletresponse response, @PathVariable String token) {logger.info ("Spring3 MVC Uploa
d file with Multipart form ");
Logger.info ("servlet Context Path:" + request.getsession (). Getservletcontext (). Getrealpath ("/"));
Userdto profiledto = Userservice.getuserbytoken (token);
String imguuid = ""; try {if (Request instanceof Multiparthttpservletrequest && profiledto.gettoken ()!= null) {Multiparthttpservle
Trequest multipartrequest = (multiparthttpservletrequest) request;
Logger.info ("spring3 MVC upload file with Multipart form");
does not work, oh my god!!
Multipartfile file = Multipartrequest.getfiles ("MyFile"). Get (0);
InputStream input = File.getinputstream ();
Long fileSize = File.getsize ();
BufferedImage image = Imageio.read (input);
Create data Transfer object Imagedto DTO = new Imagedto (); Dto.setcreateDate (new date ());
Dto.setfilename (File.getoriginalfilename ());
Dto.setimage (image);
Dto.setcreator (Profiledto.getusername ());
Dto.setfilesize (fileSize);
Dto.settype (ImageAttachmentType.CLIENT_TYPE.getTitle ());
Dto.setuuid (Uuid.randomuuid (). toString ());
Save to DB Imguuid = Imageservice.createimage (DTO);
Input.close ();
} catch (Exception e) {e.printstacktrace ();
Logger.error ("Upload image Error", e);
return imguuid; }
Android client based on httpurlconnection implementation of uploaded code, I encapsulate it into a separate class file, so that everyone can use directly, as long as the upload URL and other parameters can be. The code is as follows:
Package com.demo.http;
Import Java.io.BufferedInputStream;
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.URL;
Import Java.util.Random;
Import Android.os.Handler;
Import android.util.Base64;
Import Android.util.Log; public class Uploadimagetask implements apiurlconstants {private String Requesturl = domain_address + upload_design_imag E_url;
Default private final String CRLF = "\ r \ n";
Private Handler Handler;
Private String token;
Public Uploadimagetask (String token, Handler Handler) {this.handler = Handler;
This.token = token;
Public String Execute (file...files) {InputStream inputstream = null;
HttpURLConnection urlconnection = null;
FileInputStream fileInput = null;
DataOutputStream requeststream = null;
Handler.sendemptymessage (50); try {//open connection URL url = new URL (requesturl.replace ("{token}", This.token));
URLConnection = (httpurlconnection) url.openconnection ();
Create random boundary random random = new random ();
byte[] randombytes = new BYTE[16];
Random.nextbytes (randombytes);
String boundary = base64.encodetostring (randombytes, base64.no_wrap);
/* for POST request/Urlconnection.setdooutput (TRUE);
Urlconnection.setdoinput (TRUE);
Urlconnection.setusecaches (FALSE);
Urlconnection.setrequestmethod ("POST");
Long size = (files[0].length ()/1024);
if (size >= 1000) {handler.sendemptymessage (-150);
return "error";
}//Build entity Form Urlconnection.setrequestproperty ("Connection", "keep-alive");
Urlconnection.setrequestproperty ("Content-type", "multipart/form-data;boundary=" + boundary);
Urlconnection.setrequestproperty ("Cache-control", "No-cache"); Never try to chunked mode, your need to set a lot of things//if (Size >) {//Urlconnection.setchunkedstreamin
Gmode (0); }//else {//urlconnection.setfixedlengthstreamingmode (int) FIles[0].length ());
}//End comment by Zhigang on 2016-01-19/* upload file stream/fileInput = new FileInputStream (files[0));
Requeststream = new DataOutputStream (Urlconnection.getoutputstream ());
String nikename = "MyFile";
Requeststream = new DataOutputStream (Urlconnection.getoutputstream ());
Requeststream.writebytes ("--" + boundary + CRLF); Requeststream.writebytes ("Content-disposition:form-data; Name=\ "" + nikename + "\";
Filename=\ "" + files[0].getname () + "\" + CRLF);
Requeststream.writebytes ("Content-type:" + getmimetype (files[0)) + CRLF);
Requeststream.writebytes (CRLF);
Write image byte content int bytesread;
byte[] buffer = new byte[8192];
Handler.sendemptymessage (50);
while ((bytesread = fileinput.read (buffer))!=-1) {requeststream.write (buffer, 0, bytesread);
} requeststream.flush ();
Requeststream.writebytes (CRLF);
Requeststream.flush ();
Requeststream.writebytes ("--" + Boundary + "--" + CRLF);
Requeststream.flush ();
Fileinput.close (); Try to get response int statusCode = Urlconnection.getresponsecode ();
if (StatusCode = =) {InputStream = new Bufferedinputstream (Urlconnection.getinputstream ());
String Imageuuid = httputil.convertinputstreamtostring (InputStream);
LOG.I ("Image-uuid", "uploaded image uuid:" + imageuuid);
Handler.sendemptymessage (50);
return imageuuid;
} catch (Exception e) {e.printstacktrace ();
finally {if (InputStream!= null) {try {inputstream.close ();
catch (IOException e) {e.printstacktrace ();
} if (Requeststream!= null) {try {requeststream.close ();
catch (IOException e) {e.printstacktrace ();
} if (FileInput!= null) {try {fileinput.close ();
catch (IOException e) {e.printstacktrace ();
} if (URLConnection!= null) {urlconnection.disconnect ();
} handler.sendemptymessage (50);
return null;
private string GetMimeType (file file) {string fileName = File.getname ();
if (Filename.endswith ("png") | | | filename.endswith ("PNG")) {return "image/png";else {return "image/jpg"; }
}
}
After my test, the effect of the lever!! So forget httpclient this thing, Android development doesn't need it anymore.