转载请注明出处:http://www.jianshu.com/p/48e688ce801f
欢迎你们关注个人知乎专栏:https://zhuanlan.zhihu.com/baron 以后全部文章都会在知乎专栏上首发html
最近公司项目须要在WebView
上调用手机系统相册来上传图片,开发过程当中发如今不少机器上没法正常唤起系统相册来选择图片。android
解决问题以前咱们先来讲说WebView
上传文件的逻辑:当咱们在Web页面上点击选择文件的控件(<input type="file">
)时,会回调WebChromeClient
下的openFileChooser()
(5.0及以上系统回调onShowFileChooser()
)。这个时候咱们在openFileChooser
方法中经过Intent
打开系统相册或者支持该Intent
的第三方应用来选择图片。like this:git
public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) { uploadMessage = valueCallback; openImageChooserActivity(); } private void openImageChooserActivity() { Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("image/*"); startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE); }
最后咱们在onActivityResult()
中将选择的图片内容经过ValueCallback
的onReceiveValue
方法返回给WebView
,而后经过js上传。代码以下:github
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == FILE_CHOOSER_RESULT_CODE) { Uri result = data == null || resultCode != RESULT_OK ? null : data.getData(); if (uploadMessage != null) { uploadMessage.onReceiveValue(result); uploadMessage = null; } } }
PS:
ValueCallbacks
是WebView
组件经过openFileChooser()
或者onShowFileChooser()
提供给咱们的,它里面包含了一个或者一组Uri
,而后咱们在onActivityResult()
里将Uri
传给ValueCallbacks
的onReceiveValue()
方法,这样WebView
就知道咱们选择了什么文件。web
到这里你可能要问了,说了这么多仍是没解释为何在不少机型上没法唤起系统相册或者第三方app来选择图片啊?!这是由于为了最求完美的Google攻城狮们对openFileChooser
作了屡次修改,在5.0上更是将回调方法该为了onShowFileChooser
。因此为了解决这一问题,兼容各个版本,咱们须要对openFileChooser()
进行重载,同时针对5.0及以上系统提供onShowFileChooser()
方法:app
webview.setWebChromeClient(new WebChromeClient() { // For Android < 3.0 public void openFileChooser(ValueCallback<Uri> valueCallback) { *** } // For Android >= 3.0 public void openFileChooser(ValueCallback valueCallback, String acceptType) { *** } //For Android >= 4.1 public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) { *** } // For Android >= 5.0 @Override public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { *** return true; } });
你们应该注意到onShowFileChooser()
中的ValueCallback
包含了一组Uri(Uri[])
,因此针对5.0及以上系统,咱们还须要对onActivityResult()
作一点点处理。这里不作描述,最后我再贴上完整代码。ide
当处理完这些后你觉得就万事大吉了?!当初我也这样天真,但当咱们打好release包测试的时候却又发现无法选择图片了!!!真是坑了个爹啊!!!无奈去翻WebChromeClient
的源码,发现openFileChooser()
是系统API,咱们的release包是开启了混淆的,因此在打包的时候混淆了openFileChooser()
,这就致使没法回调openFileChooser()
了。测试
/** * Tell the client to open a file chooser. * @param uploadFile A ValueCallback to set the URI of the file to upload. * onReceiveValue must be called to wake up the thread.a * @param acceptType The value of the 'accept' attribute of the input tag * associated with this file picker. * @param capture The value of the 'capture' attribute of the input tag * associated with this file picker. * * @deprecated Use {@link #showFileChooser} instead. * @hide This method was not published in any SDK version. */ @SystemApi @Deprecated public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) { uploadFile.onReceiveValue(null); }
解决方案也很简单,直接不混淆openFileChooser()
就行了。ui
-keepclassmembers class * extends android.webkit.WebChromeClient{ public void openFileChooser(...); }
支持关于上传文件的全部坑都填完了,最后附上完整源码:
(源码地址:https://github.com/BaronZ88/WebViewSample)this
public class MainActivity extends AppCompatActivity { private ValueCallback<Uri> uploadMessage; private ValueCallback<Uri[]> uploadMessageAboveL; private final static int FILE_CHOOSER_RESULT_CODE = 10000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView webview = (WebView) findViewById(R.id.web_view); assert webview != null; WebSettings settings = webview.getSettings(); settings.setUseWideViewPort(true); settings.setLoadWithOverviewMode(true); settings.setJavaScriptEnabled(true); webview.setWebChromeClient(new WebChromeClient() { // For Android < 3.0 public void openFileChooser(ValueCallback<Uri> valueCallback) { uploadMessage = valueCallback; openImageChooserActivity(); } // For Android >= 3.0 public void openFileChooser(ValueCallback valueCallback, String acceptType) { uploadMessage = valueCallback; openImageChooserActivity(); } //For Android >= 4.1 public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) { uploadMessage = valueCallback; openImageChooserActivity(); } // For Android >= 5.0 @Override public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { uploadMessageAboveL = filePathCallback; openImageChooserActivity(); return true; } }); String targetUrl = "file:///android_asset/up.html"; webview.loadUrl(targetUrl); } private void openImageChooserActivity() { Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("image/*"); startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == FILE_CHOOSER_RESULT_CODE) { if (null == uploadMessage && null == uploadMessageAboveL) return; Uri result = data == null || resultCode != RESULT_OK ? null : data.getData(); if (uploadMessageAboveL != null) { onActivityResultAboveL(requestCode, resultCode, data); } else if (uploadMessage != null) { uploadMessage.onReceiveValue(result); uploadMessage = null; } } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) { if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null) return; Uri[] results = null; if (resultCode == Activity.RESULT_OK) { if (intent != null) { String dataString = intent.getDataString(); ClipData clipData = intent.getClipData(); if (clipData != null) { results = new Uri[clipData.getItemCount()]; for (int i = 0; i < clipData.getItemCount(); i++) { ClipData.Item item = clipData.getItemAt(i); results[i] = item.getUri(); } } if (dataString != null) results = new Uri[]{Uri.parse(dataString)}; } } uploadMessageAboveL.onReceiveValue(results); uploadMessageAboveL = null; } }
源码地址:https://github.com/BaronZ88/W...
若是你们喜欢这一系列的文章,欢迎关注个人知乎专栏、GitHub、简书博客。