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

Android 拍照取得照片路徑並上傳伺服器的完整實作

編輯:關於 Android 程式設計

以下只列出關鍵程式碼。

Activity 中的拍照與存檔部分:

public void doPhoto(View view) {
    destoryBimap();
    String state = Environment.getExternalStorageState();
    if (state.equals(Environment.MEDIA_MOUNTED)) {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        startActivityForResult(intent, 1);
    } else {
        Toast.makeText(MainActivity.this, "沒有 SD 卡", Toast.LENGTH_LONG).show();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Uri uri = data.getData();
    if (uri != null) {
        this.photo = BitmapFactory.decodeFile(uri.getPath());
    }
    if (this.photo == null) {
        Bundle bundle = data.getExtras();
        if (bundle != null) {
            this.photo = (Bitmap) bundle.get("data");
        } else {
            Toast.makeText(MainActivity.this, "拍照失敗", Toast.LENGTH_LONG).show();
            return;
        }
    }

    FileOutputStream fileOutputStream = null;
    try {
        // 獲取 SD 卡根目錄
        String saveDir = Environment.getExternalStorageDirectory() + "/meitian_photos";
        // 新建目錄
        File dir = new File(saveDir);
        if (!dir.exists()) dir.mkdir();
        // 生成檔名
        SimpleDateFormat t = new SimpleDateFormat("yyyyMMddssSSS");
        String filename = "MT" + (t.format(new Date())) + ".jpg";
        // 新建檔案
        File file = new File(saveDir, filename);
        // 打開檔案輸出流
        fileOutputStream = new FileOutputStream(file);
        // 生成圖片檔案
        this.photo.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
        // 相片的完整路徑
        this.picPath = file.getPath();
        ImageView imageView = (ImageView) findViewById(R.id.showPhoto);
        imageView.setImageBitmap(this.photo);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

/** 銷毀圖片檔案 */
private void destoryBimap() {
    if (photo != null && !photo.isRecycled()) {
        photo.recycle();
        photo = null;
    }
}

這段的流程值得拆開看。doPhoto() 先呼叫 destoryBimap() 釋放上一張照片佔用的記憶體,再檢查外部儲存是否掛載,然後以既有的 IMAGE_CAPTURE Intent 叫起相機。

回到 onActivityResult() 時,取圖有兩條路徑:優先嘗試 data.getData() 取得的 Uri 並解碼檔案;若為空,則退回 data.getExtras() 中的縮圖。要注意的是,透過 Extras 傳回的只是解析度被壓縮過的縮圖,畫質明顯較差,正式專案中建議指定輸出檔案位置以取得原圖。

存檔時以「年月日 + 毫秒」組出檔名避免覆蓋,並用 try...finally 確保 FileOutputStream 一定被關閉。最後把完整路徑記在 this.picPath,供後續上傳使用。

Layout 佈局:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >
            <Button
                android:id="@+id/doPhoto"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:layout_marginBottom="10dp"
                android:text="拍照"
                android:onClick="doPhoto" />
            <TextView
                android:id="@+id/showContent"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp" />
            <ImageView
                android:id="@+id/showPhoto"
                android:layout_width="fill_parent"
                android:layout_height="250dp"
                android:scaleType="centerCrop"
                android:src="@drawable/add"
                android:layout_marginBottom="10dp" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>

接著看上傳工具類別。

以 MultipartEntityBuilder 處理 HTTP GET / POST 與檔案上傳

這裡全面改用 MultipartEntityBuilder 來組裝請求,需要引入兩個 jar:httpmime-4.3.2.jar 與 httpcore-4.3.1.jar,可自 https://hc.apache.org/downloads.cgi 下載。若某些鏡像連不上,頁面上可以挑選國內 .cn 後綴的鏡像站。

package com.ai9475.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

public class ZHttpRequest {
    public final String HTTP_GET = "GET";
    public final String HTTP_POST = "POST";

    /** 當前請求的 URL */
    protected String url = "";
    /** HTTP 請求的類型 */
    protected String requsetType = HTTP_GET;
    /** 連接請求的超時時間 */
    protected int connectionTimeout = 5000;
    /** 讀取遠程數據的超時時間 */
    protected int soTimeout = 10000;
    /** 服務端返回的狀態碼 */
    protected int statusCode = -1;
    /** 當前鏈接的字元編碼 */
    protected String charset = HTTP.UTF_8;
    /** HTTP GET 請求管理器 */
    protected HttpRequestBase httpRequest = null;
    /** HTTP 請求的配置參數 */
    protected HttpParams httpParameters = null;
    /** HTTP 請求響應 */
    protected HttpResponse httpResponse = null;
    /** HTTP 客戶端連接管理器 */
    protected HttpClient httpClient = null;
    /** HTTP POST 方式發送多段數據管理器 */
    protected MultipartEntityBuilder multipartEntityBuilder = null;
    /** 綁定 HTTP 請求的事件監聽器 */
    protected OnHttpRequestListener onHttpRequestListener = null;

    public ZHttpRequest() {}

    public ZHttpRequest(OnHttpRequestListener listener) {
        this.setOnHttpRequestListener(listener);
    }

    /** 設置當前請求的鏈接 */
    public ZHttpRequest setUrl(String url) {
        this.url = url;
        return this;
    }

    /** 設置連接超時時間(毫秒),默認 5000 */
    public ZHttpRequest setConnectionTimeout(int timeout) {
        this.connectionTimeout = timeout;
        return this;
    }

    /** 設置 socket 讀取超時時間(毫秒),默認 10000 */
    public ZHttpRequest setSoTimeout(int timeout) {
        this.soTimeout = timeout;
        return this;
    }

    /** 設置獲取內容的編碼格式,默認為 UTF-8 */
    public ZHttpRequest setCharset(String charset) {
        this.charset = charset;
        return this;
    }

    /** 獲取當前 HTTP 請求的類型 */
    public String getRequestType() {
        return this.requsetType;
    }

    /** 判斷當前是否 HTTP GET 請求 */
    public boolean isGet() {
        return this.requsetType == HTTP_GET;
    }

    /** 判斷當前是否 HTTP POST 請求 */
    public boolean isPost() {
        return this.requsetType == HTTP_POST;
    }

    /** 獲取 HTTP 請求響應信息 */
    public HttpResponse getHttpResponse() {
        return this.httpResponse;
    }

    /** 獲取 HTTP 客戶端連接管理器 */
    public HttpClient getHttpClient() {
        return this.httpClient;
    }

    /** 添加一條 HTTP 請求的 header 信息 */
    public ZHttpRequest addHeader(String name, String value) {
        this.httpRequest.addHeader(name, value);
        return this;
    }

    /** 獲取 HTTP GET 控制器 */
    public HttpGet getHttpGet() {
        return (HttpGet) this.httpRequest;
    }

    /** 獲取 HTTP POST 控制器 */
    public HttpPost getHttpPost() {
        return (HttpPost) this.httpRequest;
    }

    /** 獲取請求的狀態碼 */
    public int getStatusCode() {
        return this.statusCode;
    }

    /** 通過 GET 方式請求數據 */
    public String get(String url) throws Exception {
        this.requsetType = HTTP_GET;
        this.setUrl(url);
        this.httpRequest = new HttpGet(this.url);
        this.httpClientExecute();
        return this.checkStatus();
    }

    /** 獲取 HTTP POST 多段數據提交管理器 */
    public MultipartEntityBuilder getMultipartEntityBuilder() {
        if (this.multipartEntityBuilder == null) {
            this.multipartEntityBuilder = MultipartEntityBuilder.create();
            // 設置為瀏覽器兼容模式
            multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            // 設置請求的編碼格式
            multipartEntityBuilder.setCharset(Charset.forName(this.charset));
        }
        return this.multipartEntityBuilder;
    }

    /** 配置完要 POST 提交的數據後,執行該方法生成數據實體等待發送 */
    public void buildPostEntity() {
        HttpEntity httpEntity = this.multipartEntityBuilder.build();
        this.getHttpPost().setEntity(httpEntity);
    }

    /** 發送 POST 請求 */
    public String post(String url) throws Exception {
        this.requsetType = HTTP_POST;
        this.setUrl(url);
        this.httpRequest = new HttpPost(this.url);
        this.httpClientExecute();
        return this.checkStatus();
    }

    /** 執行 HTTP 請求 */
    protected void httpClientExecute() throws Exception {
        this.httpParameters = new BasicHttpParams();
        this.httpParameters.setParameter("charset", this.charset);
        HttpConnectionParams.setConnectionTimeout(this.httpParameters, this.connectionTimeout);
        HttpConnectionParams.setSoTimeout(this.httpParameters, this.soTimeout);
        this.httpClient = new DefaultHttpClient(this.httpParameters);
        // 啟動請求執行前的事件監聽回調(如自定義提交的字段或上傳的檔案等)
        this.getOnHttpRequestListener().onRequest(this);
        this.httpResponse = this.httpClient.execute(this.httpRequest);
        this.statusCode = this.httpResponse.getStatusLine().getStatusCode();
    }

    /** 讀取服務端返回的輸入流並轉換成字串返回 */
    public String getInputStream() throws Exception {
        InputStream inStream = this.httpResponse.getEntity().getContent();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len = -1;
        while ((len = inStream.read(buf)) != -1) {
            baos.write(buf, 0, len);
        }
        inStream.close();
        return new String(baos.toByteArray(), this.charset);
    }

    /** 關閉連接管理器釋放資源 */
    protected void shutdownHttpClient() {
        if (this.httpClient != null && this.httpClient.getConnectionManager() != null) {
            this.httpClient.getConnectionManager().shutdown();
        }
    }

    /** 監聽服務端響應事件並返回服務端內容 */
    protected String checkStatus() throws Exception {
        OnHttpRequestListener listener = this.getOnHttpRequestListener();
        String content;
        if (this.statusCode == HttpStatus.SC_OK) {
            content = listener.onSucceed(this.statusCode, this);
        } else {
            content = listener.onFailed(this.statusCode, this);
        }
        this.shutdownHttpClient();
        return content;
    }

    /** HTTP 請求操作時的事件監聽接口 */
    public interface OnHttpRequestListener {
        /** 執行請求前的 header 或其他數據配置 */
        public void onRequest(ZHttpRequest request) throws Exception;

        /** 請求響應成功時的回調,返回獲得的字串內容 */
        public String onSucceed(int statusCode, ZHttpRequest request) throws Exception;

        /** 請求響應失敗時的回調,返回失敗的提示內容 */
        public String onFailed(int statusCode, ZHttpRequest request) throws Exception;
    }

    /** 綁定 HTTP 請求的監聽事件 */
    public ZHttpRequest setOnHttpRequestListener(OnHttpRequestListener listener) {
        this.onHttpRequestListener = listener;
        return this;
    }

    /** 獲取已綁定過的 HTTP 請求監聽事件 */
    public OnHttpRequestListener getOnHttpRequestListener() {
        return this.onHttpRequestListener;
    }
}

這個封裝的設計重點在於把「請求前要準備什麼」交給 listener.onRequest() 決定。POST 的欄位與檔案都在這個回呼中組裝,完成後呼叫 buildPostEntity() 收尾;而 GET 則什麼都不用準備。所有 setter 都回傳 this,因此可以串成一行鏈式呼叫。

在 Activity 中的使用方式(同樣只寫主體):

public void doClick(View view) {
    ZHttpRequest get = new ZHttpRequest();
    get.setCharset(HTTP.UTF_8)
       .setConnectionTimeout(5000)
       .setSoTimeout(5000);
    get.setOnHttpRequestListener(new ZHttpRequest.OnHttpRequestListener() {
        @Override
        public void onRequest(ZHttpRequest request) throws Exception { }

        @Override
        public String onSucceed(int statusCode, ZHttpRequest request) throws Exception {
            return request.getInputStream();
        }

        @Override
        public String onFailed(int statusCode, ZHttpRequest request) throws Exception {
            return "GET 請求失敗:statusCode " + statusCode;
        }
    });

    ZHttpRequest post = new ZHttpRequest();
    post.setCharset(HTTP.UTF_8)
        .setConnectionTimeout(5000)
        .setSoTimeout(10000);
    post.setOnHttpRequestListener(new ZHttpRequest.OnHttpRequestListener() {
        private String CHARSET = HTTP.UTF_8;
        private ContentType TEXT_PLAIN = ContentType.create("text/plain", Charset.forName(CHARSET));

        @Override
        public void onRequest(ZHttpRequest request) throws Exception {
            // 設置發送請求的 header 信息
            request.addHeader("cookie", "abc=123;456=愛就是幸福;");
            // 配置要 POST 的數據
            MultipartEntityBuilder builder = request.getMultipartEntityBuilder();
            builder.addTextBody("p1", "abc");
            builder.addTextBody("p2", "中文", TEXT_PLAIN);
            builder.addTextBody("p3", "abc中文cba", TEXT_PLAIN);
            if (picPath != null && !"".equals(picPath)) {
                builder.addTextBody("pic", picPath);
                builder.addBinaryBody("file", new File(picPath));
            }
            request.buildPostEntity();
        }

        @Override
        public String onSucceed(int statusCode, ZHttpRequest request) throws Exception {
            return request.getInputStream();
        }

        @Override
        public String onFailed(int statusCode, ZHttpRequest request) throws Exception {
            return "POST 請求失敗:statusCode " + statusCode;
        }
    });

    TextView textView = (TextView) findViewById(R.id.showContent);
    String content = "初始內容";
    try {
        if (view.getId() == R.id.doGet) {
            content = get.get("https://www.baidu.com");
            content = "GET數據:isGet: " + (get.isGet() ? "yes" : "no") + " =>" + content;
        } else {
            content = post.post("https://192.168.1.6/test.php");
            content = "POST數據:isPost" + (post.isPost() ? "yes" : "no") + " =>" + content;
        }
    } catch (IOException e) {
        content = "IO異常:" + e.getMessage();
    } catch (Exception e) {
        content = "異常:" + e.getMessage();
    }
    textView.setText(content);
}

其中 picPath 就是前面拍照後取得的 SD 卡圖片路徑(字串型別)。這裡有個實務細節:上傳中文文字欄位時務必明確指定 ContentType 與字元集,否則伺服器端收到的可能是亂碼。

另外提醒,request.getInputStream() 這類網路操作不能放在主執行緒執行。範例為了聚焦請求組裝而寫得精簡,實際專案請包裝在背景執行緒(或搭配非同步機制)中,並在 AndroidManifest.xml 補上 INTERNET 權限。

佈局面頁 activity_main.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >
            <Button
                android:id="@+id/doGet"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:layout_marginBottom="10dp"
                android:text="GET請求"
                android:onClick="doClick" />
            <Button
                android:id="@+id/doPost"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:layout_marginBottom="10dp"
                android:text="POST請求"
                android:onClick="doClick" />
            <Button
                android:id="@+id/doPhoto"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:layout_marginBottom="10dp"
                android:text="拍照"
                android:onClick="doPhoto" />
            <TextView
                android:id="@+id/showContent"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp" />
            <ImageView
                android:id="@+id/showPhoto"
                android:layout_width="fill_parent"
                android:layout_height="250dp"
                android:scaleType="centerCrop"
                android:src="@drawable/add"
                android:layout_marginBottom="10dp" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>

伺服器端這裡用 PHP 撰寫,只是簡單地把收到的資料印出來,方便確認欄位與檔案是否正確送達:

<?php
echo 'GET:<br>' . "\n";
print_r($_GET);
echo '<br>' . "\n" . 'POST:<br>' . "\n";
print_r($_POST);
echo '<br>' . "\n" . 'FILES:<br>' . "\n";
print_r($_FILES);
echo '<br>' . "\n" . 'COOKIES:<br>' . "\n";
print_r($_COOKIE);

除錯時,先確認 $_FILES 中是否有檔案、$_POST 中文字是否正確,能快速分辨問題出在客户端組裝還是伺服器接收。

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