Local:
Look at the project structure first
Mainactivity.java
Package Com.huxq.uploadexample;import Java.io.file;import Android.annotation.suppresslint;import Android.app.activity;import Android.app.progressdialog;import Android.os.bundle;import android.os.Environment; Import Android.os.handler;import android.os.message;import Android.util.log;import Android.view.view;import Android.widget.toast;public class Mainactivity extends Activity implements Onuploadlistener {//server path, switch to own private String urlstring = "Http://192.168.1.2:8080/UploadTest/Upload";/** * The path of the uploaded file */string filepath;/** * uploaded filename */string file Name; ProgressDialog dialog;/** * When reading a file stream, the same progress will be repeated several times, through this flag, only in the case of progress updates will be updated UI save resources */int oldprocess; @SuppressLint (" Handlerleak ") Private Handler Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {log.i (" process " , "process" + msg.arg1);d ialog.setprogress (MSG.ARG1),//Show Dialogif (!dialog.isshowing ()) {log.i () when the first time no dialog is displayed (" Process "," show ");d Ialog.show ();} else {if (msg.arg1 = = 100) {//Prompt user to upload completed Dialog.dismiss (); Toast ("Upload completed! ");}}};}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Initprogressdialog ();} public void UpLoad (View v) {if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {//Toast (" Upload "); String Sdcardpath = Environment.getexternalstoragedirectory (). GetAbsolutePath (); FilePath = Sdcardpath + "/abook/"; File File = new file (filePath);//Here I choose the Abook folder under the fifth file upload, according to their own actual situation, otherwise it must be wrong. filename = file.list () [4];filepath + = FileName; LOG.I ("File.size", "size=" + file.list (). Length + "FilePath" + FilePath);} else {toast ("No memory Card"); return;} New Thread () {public void run () {try {String response = Httputil.sendfile (URLString, Filepath,filename, Mainactivity.this ); LOG.I ("Response", "response" + response);} catch (Exception e) {e.printstacktrace ();}};}. Start ();} @Overridepublic void Onupload (double process) {process = Process * 100;int currentprocess = (int) process;dialog.setprogre SS (currentprocess);//Avoid repeating messages, you can remove if to see what happens if (Currentprocess > oldprocess) {Message msg = Handler.obtainmessage (); msg.arg1 = (int) process; Handler.sendmessage (msg);} oldprocess = currentprocess;} public void Initprogressdialog () {dialog = new ProgressDialog (this);d Ialog.setmax (+);d ialog.setprogress (0); Dialog.setprogressstyle (progressdialog.style_horizontal);d ialog.setcancelable (false); Dialog.setcanceledontouchoutside (False);d Ialog.settitle ("Trying to upload ..."); public void Toast (String text) {Toast.maketext (Getapplicationcontext (), text, Toast.length_short). Show ();}}Httputil.java
public static string SendFile (String URLPath, string filepath,string Newname,onuploadlistener listener) throws Exception {String end = "\ r \ n"; String Twohyphens = "--"; String boundary = "******"; URL url = new URL (urlpath); HttpURLConnection con = (httpurlconnection) url.openconnection ();//download requires the parameter value of the Setdoinput method to be set to Truecon.setdoinput (true) ;//upload you need to set the parameter value of the Setdooutput method to Truecon.setdooutput (true);//Disallow httpurlconnection to use cache con.setusecaches (FALSE);// Use the POST request, you must capitalize Con.setrequestmethod ("POST"),///The following three lines set the HTTP request header information Con.setrequestproperty ("Connection", "keep-alive"); Con.setrequestproperty ("Charset", "UTF-8");//When uploading a file to the server on a mock Web page, a delimiter is required at the beginning of each file, or the delimiter needs to be specified in the HTTP request header. Boundary is any string, typically ******con.setrequestproperty ("Content-type", "multipart/form-data;boundary=" + boundary);D Ataoutputstream ds = new DataOutputStream (Con.getoutputstream ());d s.writebytes (twohyphens + boundary + end);//upload file related information , this information includes the request parameter name, upload file name, file type, but is not limited to this ds.writebytes ("Content-disposition:form-data;") + "name=\" file1\ "filename=\" "+ newName +" \ "" + end);d s.writebytes (end);//Gets the input stream of the file and transmits the file through the stream. Here I rewrite the fileinputstream, in order to listen to upload progress customfileinputstream fstream = new Customfileinputstream (FilePath); Fstream.setonuploadlistener (listener);/* Set each write 1024bytes */int buffersize = 1024;byte[] buffer = new Byte[buffersize]; int length = -1;//reads data from a file to a buffer while (length = fstream.read (buffer))! =-1) {//Writes data to DataOutputStream ds.write (buffer, 0, length);} Ds.writebytes (end);d s.writebytes (twohyphens + boundary + twohyphens + end), Fstream.close ();d s.flush ();// Get feedback from the server after the upload is complete inputstream is = Con.getinputstream (); int ch; StringBuffer B = new StringBuffer (), while ((ch = is.read ())! =-1) {b.append ((char) ch);} Ds.close (); return b.tostring ();}Customfileinputstream.java
Package Com.huxq.uploadexample;import Java.io.file;import Java.io.filedescriptor;import java.io.FileInputStream; Import Java.io.filenotfoundexception;import Java.io.ioexception;public class Customfileinputstream extends FileInputStream {private Onuploadlistener listener;private int total, done;private double process;public Customfileinputstream (file file) throws FileNotFoundException {super (file); available ();} Public Customfileinputstream (FileDescriptor FD) {super (FD); available ();} Public Customfileinputstream (String path) throws FileNotFoundException {super (path); available ();} @Overridepublic int read (byte[] buffer, int byteoffset, int byteCount) throws IOException {done + = Bytecount;process = 1.0 * DONE/TOTAL;IF (listener! = null) {listener.onupload (process);} Return super.read (buffer, byteoffset, byteCount);} public void Setonuploadlistener (Onuploadlistener listener) {This.listener = listener;} @Overridepublic int available () {try {///Get the total size of the file (super.available);} catch (IOException e) {e.printstacktrace ();} return total;}}Onuploadlistener.java
Package Com.huxq.uploadexample;public interface Onuploadlistener {void onupload (double process);
Server-side:
The server side receives the file stream through a servlet and then writes to the disk.
Upload.java
Package Com.huxq.test;import Java.io.file;import Java.io.fileoutputstream;import java.io.ioexception;import Java.util.iterator;import Java.util.list;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.fileupload.fileitem;import Org.apache.commons.fileupload.fileitemfactory;import Org.apache.commons.fileupload.fileuploadexception;import org.apache.commons.fileupload.disk.DiskFileItemFactory ; Import org.apache.commons.fileupload.servlet.servletfileupload;/** * servlet implementation class Upload */@ Webservlet ("/upload") public class Upload extends HttpServlet {private static final long Serialversionuid = 1l;/** * File save path */private final String savapath= "e:\\uploads/";/** * Default constructor. */public Upload () {}/** * @see httpservlet#doget (httpservletrequest request, HttpServletResponse * response) */PRotected void doget (httpservletrequest request,httpservletresponse response) throws Servletexception, IOException { Boolean ismultipart = servletfileupload.ismultipartcontent (Request), if (Ismultipart) {Fileitemfactory factory = new Diskfileitemfactory (); Servletfileupload upload = new Servletfileupload (factory); List items;try {items = upload.parserequest (request); Iterator iter = Items.iterator ();//can receive multiple files while (Iter.hasnext ()) {Fileitem item = (Fileitem) iter.next (); if (Item.isformfield ()) {//Plain text information processing string paramname = Item.getfieldname (); String paramvalue = item.getstring (); System.out.println (paramname + ":" + paramvalue);} else {//Upload file information processing string fileName = Item.getname (); byte[] data = Item.get (); String FilePath = Savapath + fileName; File File = new file (Savapath), if (!file.exists ()) {file.mkdirs ();} System.out.println ("FilePath:" + FilePath); File File2 = new file (FilePath), if (File2.exists ()) File2.delete (); FileOutputStream fos = new FileOutputStream (file2); fos.write (data); Fos.close ();}} Response.getwriter (). Write ("upload_success");} catch (Fileuploadexception e) {e.printstacktrace (); Response.getwriter (). Write ("upload_failed");}} /** * @see Httpservlet#dopost (httpservletrequest request, HttpServletResponse * response) */protected void DoPost (HTT Pservletrequest request,httpservletresponse response) throws Servletexception, IOException {doget (request, Response);}}
Two jar packages are required here, Commons-fileupload-1.3.1.jar and Commons-io-2.4.jar, respectively.
All want to say is in the code, if there is not clear can download download demo or message together to explore.
Android File upload-local + server Dragon analysis