Android uploads files to the server

Source: Internet
Author: User

The implementation of the upload files in Android is actually very simple, and in Java is the same, basically are familiar with the operation of output stream and input stream! It is also important to configure some of the parameters of Content-type! If these are all done, the upload is very simple, here is the one I wrote the Upload Tool class: Package com.spring.sky.image.upload.network; 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;import Android.util.Log;    /** * * Upload Tool class * * @author Spring Sky email:[email protected] qq:840950105 MyName: Shi Ming */public class Uploadutil {    private static final String TAG = "UploadFile"; private static final int time_out = 10 * 1000; Timeout time private static final String CHARSET = "Utf-8";            Set Encoding/** * Android upload stationery to server * * @param file * files required to be uploaded * @param requesturl * The requested Rul * @return returns the contents of the response */public static string UploadFile (file file, string requesturl) {Strin        G 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 input stream 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); if (file = null) {/** * files are not empty, package and upload the file */dataoutputstre Am dos = new DataOutputStream (CONN.GETOUTPUtstream ());                StringBuffer sb = new StringBuffer ();                Sb.append (PREFIX);                Sb.append (boundary);                Sb.append (Line_end);                 /** * Here the Key NOTE: The value inside the name is the server 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=\ "img\";                Filename=\ "" + file.getname () + "\" "+ line_end); Sb.append ("Content-type:application/octet-stream;                Charset= "+ charset + line_end);                Sb.append (Line_end);                Dos.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 (); Dos.write (Line_end.getbytes ());                Byte[] End_data = (PREFIX + boundary + PREFIX + line_end). GetBytes ();                Dos.write (End_data);                Dos.flush ();                /** * Get response code 200 = Success When the response succeeds, gets the stream of the response */int res = Conn.getresponsecode ();                LOG.E (TAG, "Response code:" + res);                if (res==200)//{LOG.E (TAG, "request Success");                InputStream input = Conn.getinputstream ();                StringBuffer sb1 = new StringBuffer ();                int SS;                while (ss = Input.read ())! =-1) {sb1.append ((char) SS);                } result = Sb1.tostring ();                LOG.E (TAG, "Result:" + result);                }//else{//LOG.E (TAG, "request Error");        }}} catch (Malformedurlexception e) {e.printstacktrace (); } CatCH (ioexception e) {e.printstacktrace ();    } return result; }} parameter is a file and a request to upload the URL, but it should be noted that because of the use of the network request, so do not forget to upload the time, to the Android client to add a access to the network permissions Oh! Another point is that we need to pay attention to: I do server-side Java EE, I found in the process of uploading, if the file's identity name is a Java keyword, and so on, the upload process, there will be a lot of location problems! So you may not use the keyword Oh! Here is the code for the activity: package com.spring.sky.image.upload; Import Java.io.file;import Com.spring.sky.image.upload.network.uploadutil;import Android.app.activity;import Android.app.alertdialog;import Android.app.dialog;import Android.content.contentresolver;import Android.content.dialoginterface;import Android.content.intent;import Android.database.cursor;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.net.uri;import Android.os.Bundle; Import Android.provider.mediastore;import Android.util.log;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.ImageView; /** * Activity Upload interface * * @author spring Sky email:[email protected] QQ:840950105 MyName: Shi Ming zheng * */public class Mainactivity extends Activity implements Onclicklistener {private static final    String TAG = "Uploadimage";    private static String Requesturl = "Http://192.168.1.14:8080/SetBlobData/img!up";    Private Button selectimage, uploadimage;     Private ImageView ImageView;     Private String Picpath = null; /** called when the activity is first created.        */@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);         Setcontentview (R.layout.main);        Selectimage = (Button) This.findviewbyid (r.id.selectimage);        Uploadimage = (Button) This.findviewbyid (r.id.uploadimage);        Selectimage.setonclicklistener (this);         Uploadimage.setonclicklistener (this);     ImageView = (ImageView) This.findviewbyid (R.id.imageview);              } @Override public void OnClick (View v) {switch (V.getid ()) {r.id.selectimage:/*** * This is called Android built-in IntenT, to filter the picture file, but also can filter other */Intent Intent = new Intent ();            Intent.settype ("image/*");            Intent.setaction (intent.action_get_content);            Startactivityforresult (Intent, 1);        Break            Case R.id.uploadimage:file File = new file (Picpath);                if (file = null) {String request = uploadutil.uploadfile (file, Requesturl);            Uploadimage.settext (Request);        } break;        Default:break; }} @Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {if (RESULTC Ode = = ACTIVITY.RESULT_OK) {/** * When the selected picture is not empty, the way to get to the picture */URI uri = DATA.G            Etdata ();            LOG.E (TAG, "uri =" + uri);                 try {string[] Pojo = {MediaStore.Images.Media.DATA};                cursor cursor = managedquery (URI, pojo, NULL, NULL, NULL); if (CURsor! = null) {Contentresolver CR = This.getcontentresolver ();                    int colunm_index = cursor. Getcolumnindexorthrow (MediaStore.Images.Media.DATA);                    Cursor.movetofirst ();                    String path = cursor.getstring (Colunm_index); /*** * Here to add such a judgment is mainly for the third party software selection, such as: Using a third-party file Manager, you choose the file is not necessarily a picture, * So, we judge the file suffix name such as                        If the result is a picture format, then you can */if (path.endswith ("jpg") | | | path.endswith ("PNG") {                        Picpath = path;                        Bitmap Bitmap = Bitmapfactory.decodestream (cr. Openinputstream (URI));                    Imageview.setimagebitmap (bitmap);                    } else {alert ();                }} else {alert ();        }} catch (Exception e) {}} Super.onactivityresult (Requestcode, ResultCode, data); private void alert () {Dialog Dialog = new Alertdialog.builder (this). Settitle ("hint"). Setmessag  E ("You are not selecting a valid picture"). Setpositivebutton ("OK", new Dialoginterface.onclicklistener () {public                    void OnClick (Dialoginterface dialog, int which) {picpath = null;        }}). Create ();    Dialog.show (); }}layout code: <?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com /apk/res/android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" fill_p Arent "> <button android:id=" @+id/selectimage "android:layout_width=" Fill_parent "Android:lay        out_height= "Wrap_content" android:text= "select Picture"/> <button android:id= "@+id/uploadimage" Android:layout_width= "Fill_parent" android:layout_height= "wrap_content" android:text= "Upload image"/> <imageview android:id= "@+id/imageview" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content"/></linearlayout> above is Android upload pictures of all the code, if you want to upload other files, you can modify the filter conditions can be, at the same time the file type must be consistent with the server-side file type, or upload will fail!

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.