Webview中的网页中有上传文件按钮,选取文件后上传,测试时发现选视频和图片时能够上传,但是选择其他文本文件是不能上传。
用其他浏览器测试网站发现可以上传文档。
public class MyWebChromeClient extends WebChromeClient {
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
openFileInput(null, filePathCallback, false);
return true;
}
}
protected void openFileInput(final ValueCallback<Uri> fileUploadCallbackFirst, final ValueCallback<Uri[]> fileUploadCallbackSecond, final boolean allowMultiple) {
if (mFileUploadCallbackHighVersion != null) {
mFileUploadCallbackHighVersion.onReceiveValue(null);
}
mFileUploadCallbackHighVersion = fileUploadCallbackSecond;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("file/*");
Intent intent = new Intent(Intent.ACTION_CHOOSER);
intent.putExtra(Intent.EXTRA_INTENT,i);
intent.putExtra(Intent.EXTRA_TITLE,"file Chooser");
startActivityForResult(intent,100);
//startActivityForResult(Intent.createChooser(i, "file chooser"), 100);
}
public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) {
if (requestCode == 100) {
if (resultCode == Activity.RESULT_OK) {
if (intent != null) {
if (mFileUploadCallbackHighVersion != null) {//Android 5.0及以上版本
Uri[] dataUris = null;
try {
if (intent.getDataString() != null) {
String s = Uri.decode(intent.getDataString());
dataUris = new Uri[]{Uri.parse(s)};
} else {
if (Build.VERSION.SDK_INT >= 16) {
if (intent.getClipData() != null) {
final int numSelectedFiles = intent.getClipData().getItemCount();
dataUris = new Uri[numSelectedFiles];
for (int i = 0; i < numSelectedFiles; i++) {
dataUris[i] = intent.getClipData().getItemAt(i).getUri();
}
}
}
}
} catch (Exception ignored) {
}
mFileUploadCallbackHighVersion.onReceiveValue(dataUris);
mFileUploadCallbackHighVersion = null;
}
}
} else {
//这里mFileUploadCallbackFirst跟mFileUploadCallbackSecond在不同系统版本下分别持有了
//WebView对象,在用户取消文件选择器的情况下,需给onReceiveValue传null返回值
//否则WebView在未收到返回值的情况下,无法进行任何操作,文件选择器会失效
if (mFileUploadCallbackHighVersion != null) {
mFileUploadCallbackHighVersion.onReceiveValue(null);
mFileUploadCallbackHighVersion = null;
}
}
}
}