Android WebView那些坑之上传文件示例
作者:BaronZhang 发布时间:2022-10-29 02:31:15
最近公司项目需要在WebView上调用手机系统相册来上传图片,开发过程中发现在很多机器上无法正常唤起系统相册来选择图片。
解决问题之前我们先来说说WebView上传文件的逻辑:当我们在Web页面上点击选择文件的控件(<input type="file">)时,会回调WebChromeClient下的openFileChooser()(5.0及以上系统回调onShowFileChooser())。这个时候我们在openFileChooser方法中通过Intent打开系统相册或者支持该Intent的第三方应用来选择图片。like this:
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上传。代码如下:
@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就知道我们选择了什么文件。
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;
}
});
到这里你可能要问了,说了这么多还是没解释为什么在很多机型上无法唤起系统相册或者第三方app来选择图片啊?!这是因为为了最求完美的Google攻城狮们对openFileChooser做了多次修改,在5.0上更是将回调方法该为了onShowFileChooser。所以为了解决这一问题,兼容各个版本,我们需要对openFileChooser()进行重载,同时针对5.0及以上系统提供onShowFileChooser()方法:
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()做一点点处理。这里不做描述,最后我再贴上完整代码。
当处理完这些后你以为就万事大吉了?!当初我也这样天真,但当我们打好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()就好了。
-keepclassmembers class * extends android.webkit.WebChromeClient{
public void openFileChooser(...);
}
支持关于上传文件的所有坑都填完了,最后附上完整源码:
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;
}
}
源码地址: http://xiazai.jb51.net/201701/yuanma/WebViewSample_jb51.rar
来源:https://segmentfault.com/a/1190000008142462
![](https://www.aspxhome.com/images/zang.png)
![](https://www.aspxhome.com/images/jiucuo.png)
猜你喜欢
- 前言项目使用redis作为缓存数据,但面临着问题,比如,项目A,项目B都用到redis,而且用的redis都是一套集群,这样会带来一些问题。
- 本文通过介绍了Asp.Net中MVC缓存的种类,以及他们之间的区别等内容,让学习者能够深入的了解MVC缓存的原理机制,以下是具体内容:缓存是
- 本文实例讲述了Android编程之绘制文本(FontMetrics)实现方法。分享给大家供大家参考,具体如下:Canvas 作为绘制文本时,
- 实践过程效果代码public partial class Form1 : Form{ public Form1()
- ViewPager是android-support-v4.jar包里的组件。在布局文件里标签需要连包名一起写全称<android.su
- 简介大家都知道,当我们用C#来开发客户端程序的时候,总会不可避免的需要调用外部程序或者访问网站,本篇博客介绍了三种调用外部应用的方法,供参考
- 本文实例分析了C#动态生成DropDownList执行失败原因。分享给大家供大家参考。具体如下:今天研究DDL控件的动态生成的时候遇到了点问
- 本文实例讲述了C#遍历操作系统下所有驱动器的方法。分享给大家供大家参考。具体分析如下:这里先通过DriveInfo类的GetDrivers方
- 前言 需要实现环(圆)形菜单。效果预览(更多效果请下载源码体验):实现代码1.CircularMenuItemCustomCont
- 在学习和回顾该知识前,已经掌握了if语句的结构和用法。if (条件) 语句;当条件满足的情况下,if结构
- 新建一个类继承AbstractFunction,重写以下方法:executesetParametersgetReferenceKeygetA
- Spring Boot文件上传与下载在实际的Web应用开发中,为了成功上传文件,必须将表单的method设置为post,并将enctype设
- Android实现TextView超链接一共有五种方式:推荐第四种、第五种1. 直接在xml文件中配置autoLink属性(简单易用,效果单
- 前言Eureka是一种基于REST(具像状态传输)的服务,主要用于AWS云中定位服务,以实现中间层服务器的负载平衡和故障转移。本文记录一个简
- 我们第三章分析过客户端接入的流程, 这一小节带大家剖析客户端发送数据, Server读取数据的流程:首先温馨提示, 这一小节高度耦合第三章的
- 本文实例讲述了Java基于正则实现的日期校验功能。分享给大家供大家参考,具体如下:private void checkDate() thro
- Demo环境JDK8Maven3.6.3springboot2.4.3redis_version:6.2.1仓库地址https://gite
- 一:什么是classpath?classpath指的就是 *.java文件,资源文件等编译后存放的位置,对于maven项目就是指 targe
- 前言C#本身提供了很强大的控件库,但是很多控件库的功能只是一些基本的功能,就比如最简单的按钮,C#提供了最基础的按钮使用方法,但是如果要增加
- BufferedReaderBufferedReader 是缓冲字符输入流。它继承于Reader。 BufferedReader 的作用是为