Android中WebView网页上传文件设置
作者:互联网
文章目录
功能
在webView加载的网页中选择文件可以正常调用原生的选择文件功能
webView#setWebChromeClient
public class MainActivity extends AppCompatActivity {
private WebView webView;
private ValueCallback<Uri> uploadFile;
private ValueCallback<Uri[]> uploadFiles;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webview);
webView.setWebChromeClient(new WebChromeClient() {
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
Log.i("test", "openFileChooser 1");
uploadFile = uploadFile;
openFileChooseProcess();
}
// For Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsgs) {
Log.i("test", "openFileChooser 2");
uploadFile = uploadFile;
openFileChooseProcess();
}
// For Android > 4.1.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
Log.i("test", "openFileChooser 3");
uploadFile = uploadFile;
openFileChooseProcess();
}
// For Android >= 5.0
public boolean onShowFileChooser(WebView webView,
ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
Log.i("test", "openFileChooser 4:" + filePathCallback.toString());
uploadFiles = filePathCallback;
openFileChooseProcess();
return true;
}
});
webView.loadUrl("file:///android_asset/fileChooser.html");
}
private void openFileChooseProcess() {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
startActivityForResult(Intent.createChooser(i, "选择文件"), 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case 0:
if (uploadFile != null) {
Uri result = data == null || resultCode != RESULT_OK ? null
: data.getData();
uploadFile.onReceiveValue(result);
uploadFile = null;
}
if (uploadFiles != null) {
Uri result = data == null || resultCode != RESULT_OK ? null
: data.getData();
uploadFiles.onReceiveValue(new Uri[]{result});
uploadFiles = null;
}
break;
default:
break;
}
} else if (resultCode == RESULT_CANCELED) {
if (uploadFile != null) {
uploadFile.onReceiveValue(null);
uploadFile = null;
}
if (uploadFiles != null) {
uploadFiles.onReceiveValue(null);
uploadFiles = null;
}
}
}
@Override
protected void onResume() {
super.onResume();
webView.onResume();
}
@Override
protected void onPause() {
super.onPause();
webView.onPause();
}
/**
* 确保注销配置能够被释放
*/
@Override
protected void onDestroy() {
if (webView != null) {
webView.destroy();
}
super.onDestroy();
}
}
这个杀手不太累
发布了135 篇原创文章 · 获赞 57 · 访问量 22万+
私信
关注
标签:uploadFile,void,openFileChooser,webView,Android,null,上传,WebView,uploadFiles 来源: https://blog.csdn.net/zhe_ge_sha_shou/article/details/104178427