问题:在做WebView网页上传的图片的时候,发现图片无法上传,于是在网上找了各种资料,发现是系统导致的bug。下面的代码能解决这个问题。
private class MyWebChromeClient extends WebChromeClient { // Android < 3.0 调用这个方法 public void openFileChooser(ValueCallback<Uri> uploadMsg) { log.d("openFileChooser...1"); this.openFileChooser(uploadMsg, "*/*"); } // 3.0 + 调用这个方法 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { log.d("openFileChooser...2"); this.openFileChooser(uploadMsg, acceptType, null); } // Android > 4.1.1 调用这个方法 public void openFileChooser(final ValueCallback<Uri> uploadMsg, String acceptType, String capture) { log.d("openFileChooser...3"); mUploadMessage = uploadMsg; // 使用uploadMsg返回获取到的文件路径 Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("*/*"); startActivityForResult(intent, FILECHOOSER_RESULTCODE); } @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); if (newProgress == 100) { mProgressBar.setVisibility(View.GONE); } else { if (mProgressBar.getVisibility() == View.GONE) mProgressBar.setVisibility(View.VISIBLE); mProgressBar.setProgress(newProgress); } } } /** * 返回文件选择 */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == FILECHOOSER_RESULTCODE) { if (mUploadMessage == null) return; Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData(); try { mUploadMessage.onReceiveValue(/*Uri.fromFile(new File(getRealFilePath(this, result)))*/result); } catch (Exception e) { mUploadMessage = null; e.printStackTrace(); } mUploadMessage = null; } } /** * 根据uri获取图片的真真实路径 * * @param context * @param uri * @return */ private String getRealFilePath(Context context, Uri uri) { if (null == uri) return null; final String scheme = uri.getScheme(); String data = null; if (scheme == null) { data = uri.getPath(); } else if (ContentResolver.SCHEME_FILE.equals(scheme)) { data = uri.getPath(); } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) { Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null); if (null != cursor) { if (cursor.moveToFirst()) { int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); if (index > -1) { data = cursor.getString(index); } } cursor.close(); } } return data; }