LoginSignup
25
26

More than 5 years have passed since last update.

LollipopのWebViewでinput type fileで画像アップロード

Posted at

Android5.0 から WebView で画像アップのやり方が変わっていた。

stackoverflowにあるように実装してみた。

WebChromeClient に Lollipop 用の画像のアルバム選択メソッドを追加する。
新しいAPIを使うので build.gradle の compileSdkVersion を 21 以上に上げる。

private final static int FILECHOOSER_RESULTCODE = 1;
private ValueCallback<Uri[]> uploadMessage;

@Override
protected void onCreate(Bundle savedInstanceState) {
....
   webView.setWebChromeClient(new WebChromeClient() {

        public boolean onShowFileChooser(WebView webView,
                                         ValueCallback<Uri[]> filePathCallback,
                          WebChromeClient.FileChooserParams fileChooserParams)
        {

            if( uploadMessage != null) {
                uploadMessage.onReceiveValue(null);
                uploadMessage = null;
            }
            uploadMessage = filePathCallback;
            Intent intent = fileChooserParams.createIntent();
            try {
                WebActivity.this.startActivityForResult(intent,
                                                        FILECHOOSER_RESULTCODE);
            } catch (ActivityNotFoundException e) {
                uploadMessage = null;
                return false;
            }
            return true;
        }
   });

...

これでHTMLの input type file タグを突くとフォトアルバムが開いてくれる。
後は画像をチョイスした後タグのinputに入るように処理を書く。

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if( requestCode == FILECHOOSER_RESULTCODE ) {
            if( uploadMessage == null) {
                return; 
            }
            uploadMessage.onReceiveValue(
                WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
            uploadMessage = null;
        }
   }

これで Lollipop でもアルバムから画像アップロードが出来るようになった。
なんかわからんが、うまく出来てるな〜。

Android 4 の処理も onActivityResult に置く時は、このコードを
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP とかで切り替わるようにする。

== じゃないのは、使っている SDK が 22 なのに、Build.VERSION_CODES.LOLLIPOP が 21 だから。
う〜ん、将来に禍を残さないためにはどーしたもんだろか?

25
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
26