1. 程式人生 > >Android實現檔案上傳(使用Android-ansync-http)

Android實現檔案上傳(使用Android-ansync-http)

Android端實現檔案的上傳,程式碼如有雷同純屬開源!

服務端實現(使用Servlet):

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doPost(request, response);
}

關鍵看這裡

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if
(isMultipart) {// 判斷提交上來的資料是否是表單的資料 //檔案存放位置:服務目錄下的upload(如:預設TomCat部署目錄X:\Workspace\.metadata\.me_tcat\webapps\工程名\upload) String realPath = getServletContext().getRealPath("upload"); File dir = new File(realPath); if (!dir.exists()) { dir.mkdir(); } DiskFileItemFactory factory = new
DiskFileItemFactory();// 1、建立一個DiskFileItemFactory工廠 ServletFileUpload upload = new ServletFileUpload(factory);// 2、建立一個檔案上傳解析器 upload.setHeaderEncoding("utf-8");//編碼方式 try { // 4、使用ServletFileUpload解析器解析上傳的資料,解析結果是一個List<FileItem> // 集合,每一個FileItem對應一個Form表單的輸入項
List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) {//如果是文字 String name = item.getFieldName(); String value = item.getString("utf-8");//以utf-8進行編碼 System.out.println(name); } else {// 如果是檔案 String filename = item.getName(); // System.out.println("filename=" + filename); if (null == filename || "".equals(filename.trim())) { continue; } filename = filename.substring(filename .lastIndexOf("\\") + 1);//將檔名剪出 InputStream is = item.getInputStream();//得到上傳的輸入流 FileOutputStream out = new FileOutputStream("F:\\" + filename);//建立寫入磁碟的輸出流 byte[] b = new byte[1024 * 1024];//緩衝區 int len = 0; while ((len = is.read(b)) != -1) { out.write(b, 0, len); out.flush(); } is.close(); out.close(); // 處理檔案上傳時生成的臨時檔案 item.delete(); } } } catch (Exception e) { e.printStackTrace(); } } }

別忘了在web.xml註冊servlet

<servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>UpLoadServlet</servlet-name>
    <servlet-class>com.ql.UpLoadServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>UpLoadServlet</servlet-name>
    <url-pattern>/UpLoadServlet</url-pattern>
  </servlet-mapping>

伺服器端完工。。。

Android端

介面:
這裡寫圖片描述

package com.ql.fileuploaddemo;

import java.io.File;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import cz.msebera.android.httpclient.Header;

public class MainActivity extends Activity {

    private static final int FILE_SELECT_CODE = 0;

    protected static final String TAG = "QL";

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                String path = (String) msg.obj;
                editText.setText(path);
            }
            if (msg.what == 2) {
                int progress = (int) msg.arg1;
                MainActivity.this.progressBar.setProgress(progress);
                int a = msg.arg2;
                textView.setText(a + "%");
            }
            if (msg.what == 3) {
                String string = (String) msg.obj;
                textView2.setText("" + string);
            }
        }
    };

    private EditText editText;
    private ProgressBar progressBar;
    private TextView textView;

    private TextView textView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = (EditText) findViewById(R.id.editText1);
        progressBar = (ProgressBar) findViewById(R.id.progressBar1);
        textView = (TextView) findViewById(R.id.textView1);
        textView2 = (TextView) findViewById(R.id.textView2);

        Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showFileChooser();
            }
        });

        Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                UpLoad();
            }
        });
    }

    /**
     * 上傳
     */
    protected void UpLoad() {
        progressBar.setProgress(0);
        AsyncHttpClient client = new AsyncHttpClient();//例項化上傳物件
        String url = "http://10.86.30.38:8080/UpLoad/UpLoadServlet";//url組成:ip:埠 + 服務端工程名 + servlet名
        String path = editText.getText().toString().trim();

        if (null != path && "" != path) {
            File file = new File(path);
            if (file.exists() && file.length() > 0) {
                RequestParams params = new RequestParams();
                try {
                    params.put("profile", file);//將檔案加入引數
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //上傳檔案
                client.post(url, params, new AsyncHttpResponseHandler() {

                    @Override//失敗的監聽
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                        Message msg = handler.obtainMessage();
                        msg.what = 3;
                        msg.obj = "上傳失敗!";
                        handler.sendMessage(msg);
                        error.printStackTrace();
                    }

                    @Override//成功的監聽
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        Message msg = handler.obtainMessage();
                        msg.what = 3;
                        msg.obj = "上傳成功!";
                        handler.sendMessage(msg);
                    }

                    @Override//動態變化
                    public void onProgress(final long bytesWritten, final long totalSize) {
                        super.onProgress(bytesWritten, totalSize);
                        progressBar.setMax((int) totalSize);
                        float a = (float) bytesWritten / (float) totalSize;
                        Message msg = handler.obtainMessage();
                        msg.what = 2;
                        msg.arg1 = (int) bytesWritten;
                        msg.arg2 = (int) (a * 100f);
                        handler.sendMessage(msg);
                    }
                });
            }

        }
    }

    /**
     * 選擇檔案
     */
    private void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");//過濾檔案型別(所有)
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        try {
            startActivityForResult(Intent.createChooser(intent, "請選擇檔案!"), FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(this, "未安裝檔案管理器!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        case FILE_SELECT_CODE:
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                String path = FileUtils.getPath(this, uri);//得到檔案路徑
                Message msg = handler.obtainMessage();
                msg.what = 1;
                msg.obj = path;
                handler.sendMessage(msg);
            }
            break;
        }
    }

    /**
     * 檔案工具類
     * @author ql
     *
     */
    static class FileUtils {
        public static String getPath(Context context, Uri uri) {

            if ("content".equalsIgnoreCase(uri.getScheme())) {
                String[] projection = { "_data" };
                Cursor cursor = null;

                try {
                    cursor = context.getContentResolver().query(uri, projection, null, null, null);
                    int column_index = cursor.getColumnIndexOrThrow("_data");
                    if (cursor.moveToFirst()) {
                        return cursor.getString(column_index);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }
            return null;
        }
    }

}

別忘了給許可權

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

效果:
這裡寫圖片描述