第一步:
webView.getSettings().setJavaScriptEnabled(true);
第二步:
webView.setWebChromeClient(new WebChromeClient() { //扩展浏览器上传文件 //3.0++版本 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { openFileChooserImpl(uploadMsg, acceptType); } //3.0--版本 public void openFileChooser(ValueCallback<Uri> uploadMsg) { openFileChooserImpl(uploadMsg, null); } public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { openFileChooserImpl(uploadMsg, acceptType); } // For Android > 5.0 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> uploadMsg, FileChooserParams fileChooserParams) { String[] acceptTypes = fileChooserParams.getAcceptTypes(); openFileChooserImplForAndroid5(uploadMsg, acceptTypes); return true; }});
//acceptType即是web端要求的文件类型,一般有
图片:image/*
视频:video/*
图片:image/jpeg,image/gif,image/png
第三步:设置类型
private void openFileChooserImpl(ValueCallback<Uri> uploadMsg, String acceptType) { mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); if (acceptType != null) { i.putExtra(Intent.EXTRA_MIME_TYPES, new String[]{acceptType}); } startActivityForResult(Intent.createChooser(i, "文件选择"), FILECHOOSER_RESULTCODE); } private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg, String[] acceptTypes) { mUploadMessageForAndroid5 = uploadMsg; Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); contentSelectionIntent.setType("*/*"); if (acceptTypes != null) { contentSelectionIntent.putExtra(Intent.EXTRA_MIME_TYPES, acceptTypes);//支持多类型 } Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); chooserIntent.putExtra(Intent.EXTRA_TITLE, "文件选择"); startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE_FOR_ANDROID_5); }
第四步:反馈给web
@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); Logger.d("result:" + result); mUploadMessage = null; } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) { if (null == mUploadMessageForAndroid5) return; Uri result = (intent == null || resultCode != RESULT_OK) ? null : intent.getData(); if (result != null) { mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result}); Logger.d("result5:" + result); } else { mUploadMessageForAndroid5.onReceiveValue(new Uri[]{}); } mUploadMessageForAndroid5 = null; } }