Android端上傳檔案到Web伺服器

來源:互聯網
上載者:User

標籤:

本文中主要就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伺服器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.