Android implementation upload file to server instance detailed _android

Source: Internet
Author: User
Tags http request

This example realizes every 5 seconds to upload, through the server to obtain the mobile phone uploaded file information and do the corresponding processing; using ANDROID+STRUTS2 technology.

One, the Android side implementation file upload
1, 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 = Filname;
    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;
  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, encapsulating uploaded files 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 Administrator */public class Sockethttprequester {/** * directly submit data to server via HTTP protocol, as follows Form submission Function: * <form method=post 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 type= "file" name= "Zip"/> </FORM> * @param path upload path (note: Avoid using lo Calhost or 127.0.0.1 Such a path test, because it will point to the phone simulator, you can use http://www.iteye.cn or http://192.168.1.101:8083 path test) * @param params The request parameter key is the parameter name, value is the argument values * @param file Upload/public static Boolean post (String path, map<string, string> par AMS, formfile[] files) throws exception{final String BOUndary = "---------------------------7da2137580612";
    Data separator Line Final String endline = "--" + Boundary + "--\r\n";//Data end sign int filedatalength = 0;
       for (Formfile uploadfile:files) {//Get 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 () + "\ \ r \ n");
       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 textEntity Data textentity.append for type parameters ("---");
      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"); //Calculates the total length of the Entity data transmitted to the server int datalength = textentity.tostring (). GetBytes (). length + filedatalength + endline.getbytes (
    
    ). 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 HTTP request header send 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, a carriage return line outstream.write ("\ r \ n") is written according to the HTTP protocol. GetBytes ());      
    Send the Entity data of all text types Outstream.write (textentity.tostring (). GetBytes ());
       The Entity data for all file types is sent 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 () + "\ \ r \ n");
       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, 1024))!=-1) {outstream.write (buffer, 0, Len);
       } uploadfile.getinstream (). Close ();
       }else{Outstream.write (Uploadfile.getdata (), 0, Uploadfile.getdata (). length);
    } outstream.write ("\ r \ n". GetBytes ());
    
    Send the data end sign below, indicating that the data has been terminated outstream.write (Endline.getbytes ());
    BufferedReader reader = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); if (Reader.readline (). IndexOf ("200") ==-1) {//Read the data returned by the Web server to determine if the request code is 200 ifNot 200, on behalf of 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 using 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 such path test) * @param params request parameter key is the parameter name, value is an argument value * @param file Upload/public static Boolean Post (String path, map<string, string> params, formfile file) throws exception{return post (path, params, new Fo
  Rmfile[]{file});

 }
}

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

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 pictures 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", "John");
      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"/>
  <uses-permission android:name= "Android.permission.INTERNET"/> 

</manifest> 

Start the emulator and run as follows:

Second, server-side to get the Android side uploaded file information

1), a new Web project named upload, the directory structure is as follows

Note: Remember to add the Struts2 jar package, the jar you need to add is as follows

2), the new action class, named Uploadaction, the contents are as follows

Package com.ljq.action;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;

Import java.io.IOException;

Import Javax.servlet.http.HttpServletRequest;

Import Org.apache.struts2.ServletActionContext;

Import Com.opensymphony.xwork2.ActionSupport;  /** * Get the information uploaded by Android * * @author Administrator */@SuppressWarnings ("Serial") public class Uploadaction extends
  Actionsupport {///upload file domain private file image;
  Upload file type private String imagecontenttype;
  Encapsulates the upload file name private String imagefilename;

  Attributes that accept dependency injection are private String savepath;
    @Override public String Execute () {httpservletrequest request=servletactioncontext.getrequest ();
    FileOutputStream fos = null;
    FileInputStream FIS = null;
      try {System.out.println ("Get generic information from the Android side:");
      System.out.println ("User name:" +request.getparameter ("username"));
      System.out.println ("Password:" +request.getparameter ("pwd")); System.out.println ("Age:" +request.getparameter("Age"));
      SYSTEM.OUT.PRINTLN ("FileName:" +request.getparameter ("filename"));
      System.out.println ("Get the file information from the Android side:");
      System.out.println ("File storage directory:" +getsavepath ());
      System.out.println ("File name:" +imagefilename);
      SYSTEM.OUT.PRINTLN ("File Size:" +image.length ());
      
      System.out.println ("File type:" +imagecontenttype);
      FOS = new FileOutputStream (Getsavepath () + "/" + getimagefilename ());
      FIS = new FileInputStream (GetImage ());
      byte[] buffer = new byte[1024];
      int len = 0;
      while (len = fis.read (buffer))!=-1) {fos.write (buffer, 0, Len);
    } System.out.println ("File upload succeeded");
      catch (Exception e) {System.out.println ("File upload failed");
    E.printstacktrace ();
    Finally {close (FOS, FIS);
  return SUCCESS; /** * File Storage directory * * @return/public String Getsavepath () throws exception{return Servletactioncont 
  Ext.getservletcontext (). Getrealpath (Savepath); } public void SetsavepatH (String savepath) {this.savepath = Savepath;
  Public File GetImage () {return image;
  public void SetImage (File image) {this.image = image;
  Public String Getimagecontenttype () {return imagecontenttype;
  } public void Setimagecontenttype (String imagecontenttype) {this.imagecontenttype = Imagecontenttype;
  Public String Getimagefilename () {return imagefilename;
  } public void Setimagefilename (String imagefilename) {this.imagefilename = Imagefilename; private void Close (FileOutputStream fos, FileInputStream fis) {if (FIS!= null) {try {fis.close (
        );
      Fis=null;
        catch (IOException e) {System.out.println ("FileInputStream shutdown failed");
      E.printstacktrace ();
        } if (fos!= null) {try {fos.close ();
      Fis=null;
        catch (IOException e) {System.out.println ("FileOutputStream shutdown failed");
      E.printstacktrace ();
}
    }
  }

}
 

3), configuring Struts.xml

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE struts Public "-//apache Software foundation//dtd struts Configuration 2.0//en" "Http://struts.apache.org/dtds
    /struts-2.0.dtd "> <struts> <!--This property specifies the request suffix that requires Struts2 processing, and the default value of the property is action, that is, all requests that match *.action are handled by STRUTS2. If a user needs to specify more than one request suffix, multiple suffixes are separated by commas (,). --> <constant name= "struts.action.extension" value= "Do"/> <!--set whether the browser caches static content, the default value is True (used in production environments), the development phase is best closed --> <constant name= "Struts.serve.static.browserCache" value= "false"/> <!--when struts's configuration file is modified, The system automatically reloads the file, the default value is False (used in production environment), the development phase is best to open--> <constant name= "Struts.configuration.xml.reload" value= "true"/ > <!--development mode so that you can print more detailed error messages--> <constant name= "Struts.devmode" value= "true"/> <!--default View theme--&
  Gt <constant name= "Struts.ui.theme" value= "simple"/> <!--<constant name= "Struts.objectfactory" Spring "/>--> <!--solve garbled--> <constant name=" struts.i18n.encoding "value=The "UTF-8"/> <!--Specifies the maximum number of bytes allowed to upload files. The default value is 2097152 (2M)--> <constant name= "struts.multipart.maxSize" value= "22097152"/> <!--set up a temporary folder for uploading files, The default use of Javax.servlet.context.tempdir--> <constant name= "Struts.multipart.saveDir" value= "d:/tmp"/> <pack Age name= "Upload" namespace= "/upload" extends= "Struts-default" > <action name= "execute" class= " Com.ljq.action.UploadAction > <!--dynamically set Savepath property values--> <param name= "Savepath" >/image</param > <result name= "Success" >/WEB-INF/page/message.jsp</result> </action> </package> &L

 T;/struts>

4), configuring Web.xml

<?xml version= "1.0" encoding= "UTF-8"?> <web-app version= "2.4" xmlns= "Http://java.sun.com/xml/ns/j2ee" xmlns : xsi= "http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "http://java.sun.com/xml/ns/j2ee http:// Java.sun.com/xml/ns/j2ee/web-app_2_4.xsd "> <filter> <filter-name>struts2</filter-name>
  ;filter-class> Org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</
    url-pattern> </filter-mapping> <filter> <filter-name>strutsCleanup</filter-name> 
  <filter-class> org.apache.struts2.dispatcher.ActionContextCleanUp </filter-class> </filter> <filter-mapping> <filter-name>strutsCleanup</filter-name> <url-pattern>/*</url-patte
  
Rn> </filter-mapping>  <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-

 App>

The running structure is as follows:

Get generic information from the Android side:
User name: John
Password: Zhangsan
Age: 21
File name: 123.RMVB
Get the file information from the Android side:
File storage directory: D:\apache-tomcat-6.0.18\webapps\upload\image
File name: 123.RMVB
File Size: 3962649
File type: Application/octet-stream
File Upload Successful

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.