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

讓 Android WebView 支援 <input type="file">:檔案上傳的完整解法

編輯:關於 Android 開發

問題是怎麼出現的

前陣子做了一個活動頁面:使用者上傳一張圖片,縮放、旋轉之後點下一步填內容,最後生成一張分享圖。功能寫完、各種測試也跑過,流程都能走通,看起來沒什麼明顯問題。

結果一嵌進 App 就出狀況了。iOS 端基本還能work,Android 端卻有明顯異常。

具體症狀是:用 WebView 打開的頁面裡,如果有 <input type="file" ...> 這樣的檔案上傳元素,樣式會正常顯示,但完全點不動。

原因與解法方向

WebView 預設沒有實作檔案選擇的處理邏輯,需要由 App 端攔下這個請求並自行開啟檔案選擇器。做法是覆寫 WebChromeClient,實作它的 openFileChooser 系列方法,再把選好檔案的 Uri 回傳給 WebView。

完整 Demo 程式碼

public class MainActivity extends Activity {

    private final String host = "demo.com";
    private final String urlAddress = "https://" + host;
    private WebView web;
    private ProgressBar progressBar;
    private ValueCallback<Uri> mUploadMessage;
    private final static int FILECHOOSER_RESULTCODE = 1;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage) return;
            Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        web = (WebView) findViewById(R.id.webView1);
        progressBar = (ProgressBar) findViewById(R.id.progressBar1);

        WebSettings settings = web.getSettings();
        settings.setJavaScriptEnabled(true);
        web.loadUrl(urlAddress);
        web.setWebViewClient(new MyWebViewClient());

        web.setWebChromeClient(new WebChromeClient() {
            // 關鍵程式碼。以下幾個 openFileChooser 並沒有出現在官方 API 文件中,
            // 所以在 Eclipse 中若加上 @Override 會報錯。

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                MainActivity.this.startActivityForResult(
                        Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                MainActivity.this.startActivityForResult(
                        Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }

            // For Android 4.1+
            public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                        String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                MainActivity.this.startActivityForResult(
                        Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }
        });
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals(host)) {
                // 本站連結,交給 WebView 自行載入
                return false;
            }
            // 外部連結,另開 Activity 處理
            return true && (startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))) == null);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressBar.setVisibility(View.GONE);
        }
    }

    // 旋轉螢幕時不要重新載入
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    // 攔住返回鍵,讓 WebView 回到上一頁而不是直接關掉 Activity
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
            web.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

版面檔很簡單,一個 WebView 加一個 ProgressBar 而已,就不貼了。

幾個實作上的重點

  • 三個 openFileChooser 重載都要寫。Android 在不同版本對應不同的方法簽名,少寫一個就會在該版本上變成點不動。
  • mUploadMessage 必須在 onActivityResult 中 onReceiveValue 並清空。否則第二次點擊上傳時會拿到舊的 callback,直接失效。
  • 不要加 @Override。這些方法不在公開 API 文件中,加上編譯器會報錯(這也是為什麼網路上很多範例看起來「少了註解」的原因)。
  • 記得 onKeyDown 攔返回鍵。WebView 內部的瀏覽歷史若不接管,使用者按返回會直接退出整個 Activity,體驗很差。

還差一步:拍照上傳

和 iOS 比起來,這不算完美方案,因為它不支援直接呼叫相機拍照上傳。若要支援,還需要額外處理 file:// 與相機 Intent 的搭配、以及 Android 7.0 以後的 FileProvider 授權,屬於另一段額外的工作。

原文出處:Android:讓 WebView 支援 input: file 元素

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