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

Android WebView 無法打開本地檔案?破解 openFileChooser 的呼叫難題

編輯:關於 Android 程式設計

用 WebView 載入自己的網頁,頁面上有個 <input type="file">,點下去卻什麼都不會發生。這是 WebView 上傳圖片最經典的坑,根因在 WebChromeClient。

一、問題出在哪

翻 WebChromeClient 的源碼,會找到這麼一個方法:

/**
 * Tell the client to open a file chooser.
 *
 * @param uploadFile A ValueCallback to set the URI of the file to upload.
 *                   onReceiveValue must be called to wake up the thread.
 * @param acceptType The value of the 'accept' attribute of the input tag
 *                   associated with this file picker.
 * @param capture    The value of the 'capture' attribute of the input tag
 *                   associated with this file picker.
 * @hide
 */
public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {
    uploadFile.onReceiveValue(null);
}

看清楚最後那行:onReceiveValue(null)——預設實作就是「回傳空值、什麼都不做」。而且這個方法帶著 @hide 標記,不屬於公開 API,所以你即使繼承 WebChromeClient 也覆寫不了它。

二、解法:自己定義一個同簽名的方法

既然它存在於類別中,只是沒被公開,那我們就在自己的子類裡宣告一份同簽名的公開版本。Java 的方法解析會優先找到我們定義的那個。

public class WebChromeClientEx extends WebChromeClient {

    /** 讓 WebView 的 JS 能呼叫本地圖庫 */
    public void openFileChooser(ValueCallback<Uri> uploadFile) {
        // 部分舊版本 WebView 只會呼叫這個兩參數以下的版本
    }

    public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType) {
        // 部分版本走這裡
    }

    public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {
        // 較新版本走這裡
    }
}

宣告之後你會發現「莫名多出兩個方法」——那是因為不同 Android 版本、不同 WebView 實作(尤其是各家 ROM 內核版本差異極大)呼叫的簽名不同,所以三個都補上最保險。

三、在實際版本中實作

@Override
public void openFileChooser(ValueCallback<Uri> uploadFile,
                            String acceptType, String capture) {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("image/*");           // 依 acceptType 動態決定更嚴謹
    startActivityForResult(
            Intent.createChooser(intent, "完成操作需要選擇檔案"),
            FILECHOOSER_RESULTCODE);
}

四、别忘了 onActivityResult 的回傳

只實作 openFileChooser 是不夠的。使用者選完圖片回到頁面,WebView 還在等那個 callback。必須在 Activity 中把結果補回去:

private ValueCallback<Uri> mUploadMessage;

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == FILECHOOSER_RESULTCODE) {
        if (mUploadMessage == null) {
            return;
        }
        Uri result = (data == null || resultCode != RESULT_OK) ? null : data.getData();
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;      // 必須清空,否則下次上傳會拿到舊 callback
    }
}

並在 WebChromeClientEx 中把 uploadFile 存起來:

@Override
public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {
    mUploadMessage = uploadFile;
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("image/*");
    startActivityForResult(Intent.createChooser(intent, "選擇圖片"), FILECHOOSER_RESULTCODE);
}

五、幾個實務補充

  • API 21 以上要串接 ACTION_GET_CONTENT 與 camera:Android Lollipop 之後,WebView 會額外呼叫帶 acceptType/capture 的版本,並期待你能同時處理「拍照」與「相簿」兩個來源,因此回傳值需要支援 ClipData(多選)與 WebChromeClient.FileChooserParams.parseResult() 這種官方工具方法。
  • Android 5.0 的官方替代方案:API 21 起提供了公開的 WebChromeClient.onShowFileChooser(WebView, ValueCallback, FileChooserParams),這是官方支援的入口,能覆寫、能拿到 acceptType。若你的 minSdkVersion 允許,優先用它,上面那套反射式寫法只留給舊版本相容。
  • Activity 被回收的風險:跳去相簿期間 Activity 可能被系統回收,回來時 mUploadMessage 已為 null。可在 onSaveInstanceState 中記錄是否有未完成的上傳請求,回來後提示使用者重試。
  • 記得清理 callback:用完立刻 onReceiveValue(null) 並把引用設為 null,否則 WebView 的執行緒會一直等在那裡,同時造成記憶體洩漏。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved