由于业务需求,需要在Android APP的Webview中上传图片,默认点击网页上的input file没有反应,在网上搜索后发现了一个可用的版本:
android使用WebView来打开文件选择器 ,以下是部分代码:
public class BaseWebChromeClient extends WebChromeClient { public static final int FILECHOOSER_RESULTCODE = 10000; // For Android < 3.0 public void openFileChooser(ValueCallback<Uri> uploadMsg) { } // For Android 3.0+ public void openFileChooser(ValueCallback uploadMsg, String acceptType) { } //For Android 4.1 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { } //For Android 5.0+ public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) { return true; } public void onActivityResult(int resultCode, Intent data) { } }
class WebChromeClientAboveFive extends BaseWebChromeClient { private ValueCallback<Uri[]> mUploadCallbackAboveFive; private Activity mActivity; public WebChromeClientAboveFive(Activity activity) { this.mActivity = activity; } /** * 兼容5.0及以上 * * @param webView * @param valueCallback * @param fileChooserParams * @return */ @Override public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, android.webkit.WebChromeClient.FileChooserParams fileChooserParams) { mUploadCallbackAboveFive = valueCallback; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); mActivity.startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE); return true; } @Override public void onActivityResultInternal(int resultCode, Intent data) { if (null == mUploadCallbackAboveFive) { return; } Uri[] results = null; if (resultCode == Activity.RESULT_OK) { if (data != null) { String dataString = data.getDataString(); ClipData clipData = data.getClipData(); if (clipData != null) { int itemCount = clipData.getItemCount(); results = new Uri[itemCount]; for (int i = 0; i < itemCount; i++) { ClipData.Item item = clipData.getItemAt(i); results[i] = item.getUri(); } } if (dataString != null) { results = new Uri[]{Uri.parse(dataString)}; } } } mUploadCallbackAboveFive.onReceiveValue(results); mUploadCallbackAboveFive = null; return; } }
在Android模拟器上运行OK,可以正常上传图片,但是把APK安装到MIUI之后发现,图片无法正常显示出来,也无法上传,最终发现是文件权限的问题,在AndroidManifest.xml中加上文件权限就OK了:
<!-- 加入在SDCard中创建与删除文件的权限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <!-- 加入在SDCard中写入数据的权限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />