Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 XUtils 實作照片上傳:客戶端與伺服器端完整流程

編輯:關於 Android 程式設計

做 Android 的朋友大概都用過 XUtils。這篇我們用它做一個照片上傳的 Demo,把客戶端與伺服器端都走一遍,下一篇再從原始碼角度分析 XUtils 的 HttpUtils 到底是怎麼跑的。

先看成果:

客戶端

版面檔

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/top"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/upload_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="上傳圖片" />
    </LinearLayout>

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/top"
        android:layout_centerInParent="true" />
</RelativeLayout>

很簡單,一個按鈕加一個用來預覽圖片的 ImageView。

onCreate:建立 HttpUtils

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

    httpUtils = new HttpUtils(100000);          // 連線逾時 100 秒
    httpUtils.configCurrentHttpCacheExpiry(5000); // 快取有效期 5 秒
}

先初始化介面,再建立 HttpUtils 實例並設定逾時與快取時間。

initView:綁定事件與進度條

/**
 * 初始化 view 控制項
 */
public void initView() {
    uploadImageBt = (Button) findViewById(R.id.upload_image);
    imageView = (ImageView) findViewById(R.id.imageView);
    uploadImageBt.setOnClickListener(this);

    progressDialog = getProgressDialog(); // 取得進度條

    // 選擇框的點擊監聽:決定照片來源
    dialogListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
                case 0:
                    tempFile = new File(Environment.getExternalStorageDirectory(), getPhotoFileName());
                    startCamera(dialog); // 呼叫系統拍照
                    break;
                case 1:
                    startWall(dialog);   // 開啟系統圖庫
                    break;
                default:
                    break;
            }
        }
    };

    // 用 Handler 把進度送回主執行緒更新進度條
    mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.arg1 > 0) {
                progressDialog.setProgress(msg.arg1);
            }
        }
    };
}

選擇框的定義如下:

/**
 * 顯示選擇圖片來源的 dialog(拍照還是本地圖庫)
 */
public void showDialog(String title, String[] items) {
    AlertDialog.Builder dialog = new AlertDialog.Builder(this)
            .setTitle(title)
            .setItems(items, dialogListener);
    dialog.show();
}

拍照路徑

/**
 * 呼叫相機照相
 */
public void startCamera(DialogInterface dialog) {
    dialog.dismiss(); // 先隱藏來源選擇框

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra("camerasensortype", 2);   // 使用前置鏡頭
    intent.putExtra("autofocus", true);       // 自動對焦
    intent.putExtra("fullScreen", false);     // 非全螢幕
    intent.putExtra("showActionIcons", false);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile)); // 指定照片存放位置

    startActivityForResult(intent, PHOTO_CAMERA);
}

隱藏選擇框後開啟系統相機並做各項設定,指定存檔位置,最後以 PHOTO_CAMERA 作為 requestCode 返回。

相簿路徑

/**
 * 打開系統圖庫
 */
public void startWall(DialogInterface dialog) {
    dialog.dismiss();

    Intent intent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

    startActivityForResult(intent, PHOTO_WALL);
}

同樣先隱藏選擇框,接著叫出系統相簿列出 SD 卡上的所有圖片,以 PHOTO_WALL 作為 requestCode 返回。

onActivityResult:分流處理

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case PHOTO_CAMERA:
            // 相機拍的照片需要裁剪,且需要額外存檔
            startPhotoCut(Uri.fromFile(tempFile), 300, true);
            break;
        case PHOTO_WALL:
            if (null != data) {
                startPhotoCut(data.getData(), 300, false);
            }
            break;
        case PHOTO_STORE:
            if (null != data) {
                setPictureToImageView(data, true);
            }
            break;
        case PHOTO_NOT_STORE:
            if (null != data) {
                setPictureToImageView(data, false);
            }
            break;
        default:
            break;
    }
}

這個方法在 startActivityForResult 之後由系統回呼,上面出現的 PHOTO_CAMERA 與 PHOTO_WALL 就是剛才設定的 requestCode。

裁剪

/**
 * 將圖片裁剪到指定大小
 */
public void startPhotoCut(Uri uri, int size, boolean flag) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("crop", true);   // 允許裁剪

    intent.putExtra("aspectX", 1);   // 寬高比
    intent.putExtra("aspectY", 1);

    intent.putExtra("outputX", size); // 輸出寬
    intent.putExtra("outputY", size); // 輸出高

    intent.putExtra("return-data", true);

    if (flag == true) {
        startActivityForResult(intent, PHOTO_STORE);
    } else {
        tempIntent = intent;
        try {
            startActivityForResult(tempIntent, PHOTO_NOT_STORE);
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
}

前面幾行都是裁剪參數設定,接著用 flag 決定要不要把結果另存一份。如果 flag 為 false,代表這張圖本來就來自 SD 卡,沒有再存一次的必要,所以回傳標記是 PHOTO_NOT_STORE;如果是拍照來的(flag 為 true),才需要存檔,回傳標記為 PHOTO_STORE。兩條路徑最終都會回到 onActivityResult。

顯示與上傳

/**
 * 將圖片顯示到 ImageView 並上傳
 * @param flag 拍照取得的照片為 true,系統相簿選取的照片為 false
 */
public void setPictureToImageView(Intent data, boolean flag) {
    Bundle bundle = data.getExtras();
    if (null != bundle) {
        Bitmap bitmap = bundle.getParcelable("data");
        imageView.setImageBitmap(bitmap);

        if (flag == false) {
            // 相簿選取的圖片需要先取得真實路徑
            String path = getSelectPhotoPath(tempIntent);
            System.out.println("path: " + path);
            tempFile = new File(path);
        }

        // 無論來源為何,都要上傳
        UploadThread thread = new UploadThread();
        thread.start();

        if (flag == true) {
            savePictureToSD(bitmap); // 拍照的照片才需要另存
        }
    }
}

這個方法做了三件事:從 Intent 取出圖片顯示到 ImageView、啟動上傳執行緒、必要時把照片存回 SD 卡。

class UploadThread extends Thread {
    @Override
    public void run() {
        uploadPicture();
    }
}

uploadPicture:XUtils 登場

/**
 * 上傳圖片到伺服器
 */
public void uploadPicture() {
    RequestParams params = new RequestParams();
    params.addBodyParameter("msg", tempFile.getAbsolutePath());
    params.addBodyParameter(tempFile.getPath().replace("/", ""), tempFile);

    httpUtils.send(HttpMethod.POST, url, params, new RequestCallBack<String>() {

        @Override
        public void onStart() {
            progressDialog.show(); // 開始上傳,顯示進度條
        }

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            System.out.println("上傳失敗");
            System.out.println(arg0.toString());
            progressDialog.dismiss();
        }

        @Override
        public void onLoading(long total, long current, boolean isUploading) {
            System.out.println("current/total: " + current + "/" + total);
            int process = 0;
            if (total != 0) {
                process = (int) (current / (total / 100));
            }
            Message message = new Message();
            message.arg1 = process;
            mHandler.sendMessage(message);
            super.onLoading(total, current, isUploading);
        }

        @Override
        public void onSuccess(ResponseInfo<String> arg0) {
            System.out.println("上傳成功");
            progressDialog.dismiss();
        }
    });
}

這段就是 XUtils 的核心用法:先組 RequestParams,再呼叫 send 發請求。為了讓上傳過程更直觀,這裡接上了進度條——onStart 顯示進度條;onLoading 大約每秒觸發一次,透過 Handler 把進度包成 Message 丟給主執行緒更新(更新 UI 只能在主執行緒做,這也是 initView 裡那個 Handler 的用途);無論成功或失敗,最後都要 dismiss 掉進度條。

存檔到 SD 卡

/**
 * 將圖片保存到 SD 卡
 */
public void savePictureToSD(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    FileOutputStream fos = null;
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); // 100 表示不壓縮
    try {
        fos = new FileOutputStream(tempFile);
        fos.write(baos.toByteArray());
        fos.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != baos) {
                baos.close();
                baos = null;
            }
            if (null != fos) {
                fos.close();
                fos = null;
            }
        } catch (Exception e2) {
        }
    }
}

伺服器端

這裡用 SmartUpload 來接檔案:

public class UploadServlet extends HttpServlet {

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

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html,charset=utf-8");

        SmartUpload smartUpload = new SmartUpload();
        String msg = null;
        try {
            smartUpload.initialize(this.getServletConfig(), request, response);
            smartUpload.upload();

            msg = smartUpload.getRequest().getParameter("msg");
            System.out.println(smartUpload.getFiles().getCount());

            com.jspsmart.upload.File smartFile = smartUpload.getFiles().getFile(0);
            if (!smartFile.isMissing()) {
                String saveFileName = getServletContext().getRealPath("/")
                        + "images\\" + smartFile.getFileName();
                System.out.println(saveFileName);
                smartFile.saveAs(saveFileName, SmartUpload.SAVE_PHYSICAL);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

重點都在 doPost:先初始化 SmartUpload,呼叫 upload 準備接收;接著取出用戶上傳的第一個檔案——從 getCount() 與 getFile(0) 的用法不難看出 SmartUpload 本身支援多檔上傳;然後判斷檔案是否存在、組出存放路徑、執行存檔。

要特別注意 SmartUpload.SAVE_PHYSICAL 代表絕對路徑,所以存放路徑必須寫全,不能只給相對目錄。

web.xml 的設定:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5"
    xmlns="https://java.sun.com/xml/ns/javaee"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <servlet>
        <servlet-name>UploadServlet</servlet-name>
        <servlet-class>com.hzw.servlet.UploadServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>UploadServlet</servlet-name>
        <url-pattern>/upload</url-pattern>
    </servlet-mapping>
</web-app>

最後提醒一下:客戶端別忘了加上網路存取與 SD 卡存取的權限,這是最容易被漏掉、又最容易導致「跑起來什麼都沒發生」的一環。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved