[Android] webview 与 h5 upload(1)
最近在做一个 webview 展示 h5 表单的功能,发现 <input type="file">
无法打开 Android 媒体库选择文件
原来,是需要 override WebChromeClient() 的 onShowFileChooser(webView: WebView?,filePathCallback: ValueCallback<Array<Uri>>?,fileChooserParams: FileChooserParams?):Boolean
方法,在此处处理 filePathCallback,并返回 true。
举个例子:
binding.webView.settings.apply {
javaScriptEnabled = true
loadsImagesAutomatically = true
setSupportZoom(false)
// 允许访问文件
domStorageEnabled = true
allowContentAccess = true
allowFileAccess = true
}
binding.webView.webChromeClient = object : WebChromeClient() {
override fun onShowFileChooser(
webView: WebView?,
filePathCallback: ValueCallback<Array<Uri>>?,
fileChooserParams: FileChooserParams?
): Boolean {
this@FormFragment.filePathCallback = filePathCallback
currentFilename = "${System.currentTimeMillis()}"
try {
context.createJpgUri(currentFilename) {
// photoLauncher 是 ActivityResultContracts.TakePicture()
photoLauncher.launch(it)
}
} catch (e: Exception) {
e.printStackTrace()
filePathCallback?.onReceiveValue(null)
}
return true
}
}
此时,发现可以打开媒体库(例子中为打开摄像头,原理是一样的)