Android端上传文件到Web服务器

Posted Frank Q

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android端上传文件到Web服务器相关的知识,希望对你有一定的参考价值。

本文中主要就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();

        
    

以上是关于Android端上传文件到Web服务器的主要内容,如果未能解决你的问题,请参考以下文章

移动端图片操作——上传

android批量文件上传(android批量图片上传)

带有服务器端 php 的 Android 文件上传器

SpringCloud怎么实现web端上传超大文件

SpringCloud怎么实现web端上传超大文件

求php怎么实现web端上传超大文件