Android uploads files to the server

Source: Internet
Author: User

Upload files on the Android side

1), create a new Android project named Androidupload, the directory structure is as follows:

2), New Formfile class, used to encapsulate file information

Package Com.ljq.utils;import Java.io.file;import Java.io.fileinputstream;import java.io.FileNotFoundException;    Import java.io.inputstream;/** * Upload file */public class Formfile {/* Upload file Data */private byte[]    Private InputStream instream;    private file file;    /* File name */private String filname;    /* Request Parameter name */private String parametername;        /* Content Type */private String ContentType = "Application/octet-stream";        Public Formfile (String filname, byte[] data, String parametername, String contentType) {this.data = data;        This.filname = Filname;        This.parametername = parametername;    if (contenttype!=null) This.contenttype = ContentType; Public Formfile (String filname, File file, String parametername, String contentType) {this.filname = Filn        Ame        This.parametername = parametername;        This.file = file;        try {this.instream = new FileInputStream (file);    } catch (FileNotFoundException e) {        E.printstacktrace ();    } if (contenttype!=null) This.contenttype = ContentType;    } public file GetFile () {return file;    } public InputStream Getinstream () {return instream;    } public byte[] GetData () {return data;    } public String Getfilname () {return filname;    } public void Setfilname (String filname) {this.filname = Filname;    } public String Getparametername () {return parametername;    } public void SetParameterName (String parametername) {this.parametername = parametername;    } public String getContentType () {return contentType;    } public void setContentType (String contentType) {this.contenttype = ContentType; }    }

3), New Sockethttprequester class, package upload file to server code

Package Com.ljq.utils;import Java.io.bufferedreader;import Java.io.inputstreamreader;import java.io.OutputStream; Import Java.net.inetaddress;import java.net.socket;import java.net.url;import java.util.map;/** * Upload files to server * * @author A Dministrator * */public class Sockethttprequester {/** * directly submits data to the server via HTTP protocol, implementing the following form submission function: * <form method=p OST action= "http://192.168.1.101: 8083/upload/servlet/uploadservlet "enctype=" Multipart/form-data "> <input type=" text "name=" NAME "> <input type= "text" name= "id" > <input type= "file" name= "ImageFile"/> <input ty Pe= "file" name= "Zip"/> </FORM> * @param path upload route (note: Avoid path tests such as localhost or 127.0.0.1, as it will point to the phone simulator, you can use H     Path test such as ttp://www.iteye.cn or http://192.168.1.101:8083) * @param params request parameter key is parameter name, value is parameter value * @param file Upload files             */public static Boolean post (String path, map<string, string> params, formfile[] files) throws exception{ Final String boundary = "---------------------------7da2137580612";        Data separator Line Final String endline = "--" + Boundary + "--\r\n";//Data end flag int filedatalength = 0;             for (Formfile uploadfile:files) {//Gets the total length of the file type data StringBuilder Fileexplain = new StringBuilder ();             Fileexplain.append ("--");        Fileexplain.append (boundary);     Fileexplain.append ("\ r \ n"); Fileexplain.append ("content-disposition:form-data;name=\" "+ uploadfile.getparametername () +" \ "; filename=\" "+             Uploadfile.getfilname () + "\" \ \ "\ \ \");             Fileexplain.append ("Content-type:" + uploadfile.getcontenttype () + "\r\n\r\n");             Fileexplain.append ("\ r \ n");            Filedatalength + = Fileexplain.length ();             if (Uploadfile.getinstream ()!=null) {filedatalength + = Uploadfile.getfile (). Length ();             }else{Filedatalength + = Uploadfile.getdata (). length;        }} StringBuilder textentity = new StringBuilder ();            For (map.entry<string, string> entry:params.entrySet ()) {//Construct the Entity data of the text type parameter Textentity.append ("--");            Textentity.append (boundary);            Textentity.append ("\ r \ n"); Textentity.append ("Content-disposition:form-data;            Name=\ "" + entry.getkey () + "\" \r\n\r\n ");   Textentity.append (Entry.getvalue ());         Textentity.append ("\ r \ n"); }//Calculate the total length of entity data transferred to the server int datalength = textentity.tostring (). GetBytes (). length + filedatalength + endline.ge                Tbytes (). length;        URL url = new URL (path); int port = Url.getport () ==-1?        80:url.getport ();                   Socket socket = new Socket (Inetaddress.getbyname (Url.gethost ()), port);        OutputStream OutStream = Socket.getoutputstream ();        The following completes the sending of the HTTP request header String Requestmethod = "POST" + url.getpath () + "http/1.1\r\n";        Outstream.write (Requestmethod.getbytes ()); String accept = "Accept:image/gif, Image/jpeg, Image/pjpeg, Image/pjpeg, Application/x-shockwave-flash, application/ Xaml+xml, Application/vnd.ms-xpsdocument, APPLICATION/X-MS-XBAP, Application/x-ms-application, application/        Vnd.ms-excel, Application/vnd.ms-powerpoint, Application/msword, */*\r\n ";        Outstream.write (Accept.getbytes ());        String language = "accept-language:zh-cn\r\n"; Outstream.write (lAnguage.getbytes ()); String contenttype = "CONTENT-TYPE:MULTIPART/FORM-DATA;        boundary= "+ boundary+" \ r \ n ";        Outstream.write (Contenttype.getbytes ());        String contentlength = "Content-length:" + datalength + "\ r \ n";        Outstream.write (Contentlength.getbytes ());        String alive = "connection:keep-alive\r\n";        Outstream.write (Alive.getbytes ());        String host = "Host:" + url.gethost () + ":" + port + "\ r \ n";        Outstream.write (Host.getbytes ());        After the HTTP request header is written, write a carriage return outstream.write ("\ r \ n") according to the HTTP protocol. GetBytes ());                   Send the Entity data of all text types Outstream.write (textentity.tostring (). GetBytes ());             Send Entity data for all file types out for (Formfile uploadfile:files) {StringBuilder fileentity = new StringBuilder ();             Fileentity.append ("--");             Fileentity.append (boundary);             Fileentity.append ("\ r \ n"); Fileentity.append ("content-disposition:form-data;name=\" "+ uploadfile.getparametername() + "\"; filename=\ "" + uploadfile.getfilname () + "\" \ "\ \ \ \ \ \");             Fileentity.append ("Content-type:" + uploadfile.getcontenttype () + "\r\n\r\n");             Outstream.write (Fileentity.tostring (). GetBytes ());                 if (Uploadfile.getinstream ()!=null) {byte[] buffer = new byte[1024];                 int len = 0;                 while (len = Uploadfile.getinstream (). Read (buffer, 0, 1024x768)) (!=-1) {outstream.write (buffer, 0, Len);             } uploadfile.getinstream (). Close ();             }else{Outstream.write (Uploadfile.getdata (), 0, Uploadfile.getdata (). length);        } outstream.write ("\ r \ n". GetBytes ());                }//below sends the end of data flag indicating that the data has ended Outstream.write (Endline.getbytes ());        BufferedReader reader = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); if (Reader.readline (). IndexOf ("200") ==-1) {//reads the data returned by the Web server, determines if the request code is 200, if not 200, represents the request failed reTurn false;        } outstream.flush ();        Outstream.close ();        Reader.close ();        Socket.close ();    return true; /** * Submit data to Server * @param path upload path (note: Avoid path tests such as localhost or 127.0.0.1, as it will point to the phone simulator, you can use http://www.itcast.cn or  http://192.168.1.10:8080 path Test) * @param params request parameter key is parameter name, value is parameter value * @param file Upload Document */public static Boolean post (String path, map<string, string> params, formfile file) throws exception{return post (PATH, para    MS, new Formfile[]{file}); }}

4), New Mainactivity class, to achieve every 5 seconds upload

Package Com.ljq.activity;import Java.io.file;import Java.util.hashmap;import java.util.map;import Android.app.activity;import Android.os.bundle;import Android.os.environment;import Android.os.Handler;import Android.util.log;import Com.ljq.utils.formfile;import Com.ljq.utils.sockethttprequester;public class MainActivity    Extends Activity {private file file;    Private Handler Handler;    private static final String tag= "mainactivity";        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main);                LOG.I (TAG, "onCreate");        File = new file (Environment.getexternalstoragedirectory (), "123.rmvb");        LOG.I (TAG, "Photo file exists:" +file);        Handler=new handler ();    Handler.post (runnable);            } Runnable runnable=new Runnable () {public void run () {log.i (TAG, "Runnable run");            UploadFile (file);   Handler.postdelayed (runnable, 5000);     }        };  /** * Upload image to Server * * @param imagefile include path */public void UploadFile (File imagefile) {log.i (TAG,        "Upload start");            try {String Requesturl = "Http://192.168.1.101:8083/upload/upload/execute.do";            Request general Information map<string, string> params = new hashmap<string, string> ();            Params.put ("username", "Zhang San");            Params.put ("pwd", "Zhangsan");            Params.put ("Age", "21");            Params.put ("FileName", Imagefile.getname ());                        Upload file Formfile formfile = new Formfile (Imagefile.getname (), ImageFile, "image", "Application/octet-stream");            Sockethttprequester.post (Requesturl, params, formfile);        LOG.I (TAG, "upload success");            } catch (Exception e) {log.i (TAG, "upload error");        E.printstacktrace ();    } log.i (TAG, "Upload End"); }}

5), modify the list file

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "      package=" com.ljq.activity "      android:versioncode=" 1 "      android:versionname=" 1.0 ">    < Application android:icon= "@drawable/icon" android:label= "@string/app_name" >        <activity android:name= ". Mainactivity "                  android:label=" @string/app_name ">            <intent-filter>                <action android:name=" Android.intent.action.MAIN "/>                <category android:name=" Android.intent.category.LAUNCHER "/>            < /intent-filter>        </activity>    </application>    <uses-sdk android:minsdkversion= "4" />    

Android uploads files to the server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.