Handle file chooser android WebViews

一世执手 提交于 2021-01-29 08:53:34

问题


image

I have an issue guys. I have a webView app. Inside the app is a button that should enable user pick file from device and upload to api. Everything was handled with the web. The problem is that on the webView app, on tapping the button, nothing happens, however, when I try with a chrome browser or a browser app, it works well.

What do I need to do to ensure it works the same way as the chrome browser? I don't want to handle this functionality natively as that's the only solutions I saw online. I tried doing that anyways, but it doesn't pop out those file options like in this image

Is there an easier way to handle this?


回答1:


Try this:

private var filePathCallback: ValueCallback<Array<Uri>>? = null

override fun onCreate(savedInstanceState: Bundle?) {
        webView.webChromeClient = object: WebChromeClient() {
            override fun onShowFileChooser(webView: WebView?, filePathCallback: ValueCallback<Array<Uri>>?, fileChooserParams: FileChooserParams?): Boolean {
                startActivityForResult(fileChooserParams?.createIntent(), CHOOSE_FILE_REQUEST_CODE)
                this@MainActivity.filePathCallback = filePathCallback
                return true
            }
        }
    }

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            CHOOSE_FILE_REQUEST_CODE -> {
                if (resultCode == Activity.RESULT_OK) {
                    filePathCallback?.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data))
                    filePathCallback = null
                }
            }
        }
    }



回答2:


You have to set the webview like,

    // Other webview options
    webView.getSettings().setLoadWithOverviewMode(true);
    // Javascript inabled on webview  
    webView.getSettings().setJavaScriptEnabled(true); 
    //webView.getSettings().setUseWideViewPort(true);
     
    //Other webview settings
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(false);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setPluginState(PluginState.ON);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setSupportZoom(true); 

and need to set up custom `WebViewClient, check out the link for more details. Open file chooser in webview.

Let me know if it is working for you or not.



来源:https://stackoverflow.com/questions/62625705/handle-file-chooser-android-webviews

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!