Android WebView 不支持 H5 input type="file" 解决方法
最近因为赶项目进度,因此将本来要用原生控件实现的界面,自己做了H5并嵌入webview中。发现点击H5中inputtype="file"标签不能打开android资源管理器。
通过网络搜索发现是因为androidwebview由于考虑安全原因屏蔽了inputtype="file"这个功能。
经过不懈的努力,以及google翻译的帮助在stackoverflow中找到了解决的方法。
具体可以理解为重写webview的WebChromeClient,废话不多说直接贴代码:
privateValueCallbackmUploadMessage; publicValueCallback uploadMessage; publicstaticfinalintREQUEST_SELECT_FILE=100; privatefinalstaticintFILECHOOSER_RESULTCODE=2; webview.setWebChromeClient(newWebChromeClient(){ //For3.0+Devices(Start) //onActivityResultattachedbeforeconstructor protectedvoidopenFileChooser(ValueCallbackuploadMsg,StringacceptType) { mUploadMessage=uploadMsg; Intenti=newIntent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("image/*"); startActivityForResult(Intent.createChooser(i,"FileBrowser"),FILECHOOSER_RESULTCODE); } //ForLollipop5.0+Devices @TargetApi(Build.VERSION_CODES.LOLLIPOP) publicbooleanonShowFileChooser(WebViewmWebView,ValueCallback filePathCallback,WebChromeClient.FileChooserParamsfileChooserParams) { if(uploadMessage!=null){ uploadMessage.onReceiveValue(null); uploadMessage=null; } uploadMessage=filePathCallback; Intentintent=fileChooserParams.createIntent(); try { startActivityForResult(intent,REQUEST_SELECT_FILE); }catch(ActivityNotFoundExceptione) { uploadMessage=null; Toast.makeText(getBaseContext(),"CannotOpenFileChooser",Toast.LENGTH_LONG).show(); returnfalse; } returntrue; } //ForAndroid4.1only protectedvoidopenFileChooser(ValueCallback uploadMsg,StringacceptType,Stringcapture) { mUploadMessage=uploadMsg; Intentintent=newIntent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("image/*"); startActivityForResult(Intent.createChooser(intent,"FileBrowser"),FILECHOOSER_RESULTCODE); } protectedvoidopenFileChooser(ValueCallback uploadMsg) { mUploadMessage=uploadMsg; Intenti=newIntent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("image/*"); startActivityForResult(Intent.createChooser(i,"FileChooser"),FILECHOOSER_RESULTCODE); } }); } @Override publicvoidonActivityResult(intrequestCode,intresultCode,Intentintent) { if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) { if(requestCode==REQUEST_SELECT_FILE) { if(uploadMessage==null) return; uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode,intent)); uploadMessage=null; } } elseif(requestCode==FILECHOOSER_RESULTCODE) { if(null==mUploadMessage) return; //UseMainActivity.RESULT_OKifyou'reimplementingWebViewinsideFragment //UseRESULT_OKonlyifyou'reimplementingWebViewinsideanActivity Uriresult=intent==null||resultCode!=MainActivity.RESULT_OK?null:intent.getData(); mUploadMessage.onReceiveValue(result); mUploadMessage=null; } else Toast.makeText(getBaseContext(),"FailedtoUploadImage",Toast.LENGTH_LONG).show(); }
以上所述是小编给大家介绍的AndroidWebView不支持H5inputtype="file"解决方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!