要在Android Webview应用程序中启用文件上传功能,可以按照以下步骤进行操作:
1.在AndroidManifest.xml文件中添加以下代码以获取WRITE_EXTERNAL_STORAGE权限:
2.在Webview设置中启用JavaScript:
webView.getSettings().setJavaScriptEnabled(true);
3.为Webview设置WebChromeClient:
webView.setWebChromeClient(new WebChromeClient() {
//文件选择器数据
public void openFileChooser(ValueCallback
//创建包含传递文件URI的意图
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
//启动文件选择器
startActivityForResult(Intent.createChooser(intent, "File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android >= 3.0
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
openFileChooser(uploadMsg, acceptType, "");
}
// For Android >= 4.1
public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), FILECHOOSER_RESULTCODE);
}
// For Android > 5.0
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
mFilePathCallback = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), FILECHOOSER_RESULTCODE);
return true;
}
});
4.在onActivityResult方法中处理文件选择器意图:
@Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == FILECHOOSER_RESULTCODE) { if (resultCode == Activity.RESULT_OK && intent