本文中主要就Android端上传文件到Web服务器,做出的一个简单的Demo

1、Tomcat上部署的服务端的实现
2、Android端的代码实现

1、Tomcat服务器上面项目的部署与实现
创建一个Web Project
创建FileUploadServlet.java,当然,一下两个重要的Jar包不能够忘记!
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar

FileUploadServlet.java

import java.io.File;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;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.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;public class FileUpLoadServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        doPost(request, response);    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {         boolean isMultipart = ServletFileUpload.isMultipartContent(request);         if (isMultipart) {         String realpath = request.getSession().getServletContext()                 .getRealPath("/files");         System.out.println(realpath);         File dir = new File(realpath);         if (!dir.exists())             dir.mkdirs();         FileItemFactory factory = new DiskFileItemFactory();         ServletFileUpload upload = new ServletFileUpload(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();// 得到请求参数的名称                     String value = item.getString("UTF-8");// 得到参数值                     System.out.println(name1 + "=" + value);                 } else {                     item.write(new File(dir, System.currentTimeMillis()                             + item.getName().substring(                                     item.getName().lastIndexOf("."))));                 }             }         } catch (Exception e) {             e.printStackTrace();         }     }    }}

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、Android端的代码实现
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="16"        android:targetSdkVersion="21" />    <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="请输入上传的文件路径" />    <Button         android:onClick="upload"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="上传文件"/></LinearLayout>

导入开源项目:com.loopj.android.http;可以再Github上下载
Git地址:https://github.com/loopj/android-async-http

MainActivity.java

import java.io.File;import java.io.FileNotFoundException;import org.apache.http.Header;import com.loopj.android.http.AsyncHttpClient;import com.loopj.android.http.AsyncHttpResponseHandler;import com.loopj.android.http.RequestParams;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {    private EditText 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) throws FileNotFoundException {        String path = et_path.getText().toString().trim();        String server_upload_path = "http://192.168.3.36:8080/AndroidWebServerDemo1/FileUpLoadServlet";        File file = new File(path);        if(file.exists() && file.length() > 0) {            AsyncHttpClient client = new AsyncHttpClient();             RequestParams params = new RequestParams();            params.put("tempfile", file);            client.post(server_upload_path, params, new AsyncHttpResponseHandler() {                @Override                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {                    Toast.makeText(getApplicationContext(), "上传成功", 0).show();                }                @Override                public void onFailure(int statusCode, Header[] headers,                        byte[] responseBody, Throwable error) {                    Toast.makeText(getApplicationContext(), "上传失败", 0).show();                }            });        } else {            Toast.makeText(getApplicationContext(), "无效路径", 0).show();        }    }}

更多相关文章

  1. Android基于Http协议实现文件上传功能的方法
  2. AndroidStudio部署项目时出现错误:Instant Run requires 'Tools |
  3. Android通过setDataAndType(uri, "type")打开文件
  4. Android(安卓)MediaScanner
  5. android菜鸟学习笔记1----环境搭建
  6. Paint---PathEffect(路径效果)
  7. Android利用webservices实现图片远程上传
  8. android post数据到服务器端工具类(包括postjson字符串、键值对)
  9. emoji表情在web html上显示

随机推荐

  1. Android 天气预报图文字幕垂直滚动效果
  2. ubuntu出错,开机无法登录
  3. Android如何实现计算缓存空间大小和删除
  4. androidの读取短信内容
  5. Android(安卓)Task和Activity分析
  6. ImageView ScaleType 属性值的意义
  7. Android(安卓)Activity URL Scheme的介绍
  8. Android中Manifest.xml配置文件
  9. Android中Home键的监听和拦截示例
  10. 理解 Android 的 ONE_SHOT_MAKEFILE