Upload files to the Web server on the Android side

Source: Internet
Author: User

This article mainly on the Android side to upload files to the Web server, make a simple demo

1. Implementation of the server deployed on Tomcat
2, the code implementation of the Android side

1, Tomcat server above the deployment and implementation of the project
Create a Web Project
Create Fileuploadservlet.java, of course, two important jar packages can not be forgotten!
Commons-fileupload-1.2.2.jar
Commons-io-2.0.1.jar

Fileuploadservlet.java

ImportJava.io.File;ImportJava.io.IOException;ImportJava.util.List;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.commons.fileupload.FileItem;ImportOrg.apache.commons.fileupload.FileItemFactory;ImportOrg.apache.commons.fileupload.disk.DiskFileItemFactory;ImportOrg.apache.commons.fileupload.servlet.ServletFileUpload; Public  class fileuploadservlet extends httpservlet {    Private Static Final LongSerialversionuid =1L Public void Doget(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {doPost (request, response); } Public void DoPost(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {BooleanIsmultipart = servletfileupload.ismultipartcontent (request);if(Ismultipart) {String Realpath = Request.getsession (). Getservletcontext (). Getrealpath ("/files");         System.out.println (Realpath); File dir =NewFile (Realpath);if(!dir.exists ()) dir.mkdirs (); Fileitemfactory factory =NewDiskfileitemfactory (); Servletfileupload upload =NewServletfileupload (Factory); Upload.setheaderencoding ("UTF-8");Try{@SuppressWarnings("Unchecked") list<fileitem> items = upload.parserequest (request); for(Fileitem Item:items) {if(Item.isformfield ()) {String name1 = Item.getfieldname ();//Get the name of the request parameterString value = item.getstring ("UTF-8");//Get parameter valuesSystem.out.println (name1 +"="+ value); }Else{Item.write (NewFile (dir, System.currenttimemillis () + item.getname (). SUBSTRING ( Item.getname (). LastIndexOf (".")))); }             }         }Catch(Exception e)         {E.printstacktrace (); }     }    }}

Configuration of Web. xml

<?xml version= "1.0" encoding= "UTF-8"?><web-app version="2.5"xmlns="Http://java.sun.com/xml/ns/javaee"  xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation=" Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd ">                 <display-name></display-name>  <servlet>    <servlet-name>Fileuploadservlet</servlet-name>    <servlet-class>Com.fileupload.FileUpLoadServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>Fileuploadservlet</servlet-name>    <url-pattern>/fileuploadservlet</url-pattern>  </servlet-mapping>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></Web-app>

2, the code implementation of the Android side
Androidmanifest.xml

<?xml version="1.0"encoding="Utf-8"? ><manifest xmlns:android="Http://schemas.android.com/apk/res/android"     Package="Com.fileuploadtoserver"Android:versioncode="1"Android:versionname="1.0"> <uses-sdk android:minsdkversion="+"android:targetsdkversion="very"/> <uses-permission android:name="Android.permission.INTERNET"/> <application android:allowbackup="true"android:icon="@drawable/ic_launcher"Android:label="@string/app_name"Android:theme="@style/apptheme"> <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></manifest>

Activity_main.xml

<linearlayout xmlns:android="Http://schemas.android.com/apk/res/android"xmlns:tools="Http://schemas.android.com/tools"Android:layout_width="Match_parent"android:layout_height="Match_parent"android:orientation="Vertical"> <edittext android:id="@+id/et_uploadpath"Android:layout_width="Match_parent"android:layout_height="Wrap_content"Android:hint="Please enter the file path to upload"/> <button android:onclick="Upload"Android:layout_width="Match_parent"android:layout_height="Wrap_content"android:text="Upload file"/></linearlayout>

Import Open Source project: com.loopj.android.http; You can download it again on GitHub.
git address: https://github.com/loopj/android-async-http

Mainactivity.java

ImportJava.io.File;ImportJava.io.FileNotFoundException;ImportOrg.apache.http.Header;ImportCom.loopj.android.http.AsyncHttpClient;ImportCom.loopj.android.http.AsyncHttpResponseHandler;ImportCom.loopj.android.http.RequestParams;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.EditText;ImportAndroid.widget.Toast; Public  class mainactivity extends Activity {    PrivateEditText Et_path;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Et_path = (EditText) This. Findviewbyid (R.id.et_uploadpath); } Public void Upload(View view)throwsFileNotFoundException {String path = Et_path.gettext (). toString (). Trim (); String Server_upload_path ="Http://192.168.3.36:8080/AndroidWebServerDemo1/FileUpLoadServlet"; File File =NewFile (path);if(File.exists () && file.length () >0) {Asynchttpclient client =NewAsynchttpclient (); Requestparams params =NewRequestparams (); Params.put ("Tempfile", file); Client.post (Server_upload_path, params,NewAsynchttpresponsehandler () {@Override                 Public void onsuccess(intStatusCode, header[] headers,byte[] responsebody) {Toast.maketext (Getapplicationcontext (),"Upload succeeded",0). Show (); }@Override                 Public void onfailure(intStatusCode, header[] headers,byte[] responsebody, throwable error) {Toast.maketext (Getapplicationcontext (),"Upload failed",0). Show ();        }            }); }Else{Toast.maketext (Getapplicationcontext (),"Invalid path",0). Show (); }    }}

Upload files to the Web server on the Android side

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.