Java 从android webview上传多个文件(Kitkat和更低版本的android)
在我的应用程序中,我使用webview呈现一个网页,我需要从中向服务器上载多个文件。OnShowFileChooser()(用于棒棒糖和更高版本)工作正常,但onOpenFileChooser()(用于其他更低版本的android)。如果我将Uri数组(Uri[])传递给onValueCallback(),OnshowFileChooser()方法将不起作用。它抛出classCastException。下面是我执行所需操作时使用的代码。我需要一个解决方案来上传多个文件使用webview,这将适用于所有android版本Java 从android webview上传多个文件(Kitkat和更低版本的android),java,android,webview,filechooser,webchromeclient,Java,Android,Webview,Filechooser,Webchromeclient,在我的应用程序中,我使用webview呈现一个网页,我需要从中向服务器上载多个文件。OnShowFileChooser()(用于棒棒糖和更高版本)工作正常,但onOpenFileChooser()(用于其他更低版本的android)。如果我将Uri数组(Uri[])传递给onValueCallback(),OnshowFileChooser()方法将不起作用。它抛出classCastException。下面是我执行所需操作时使用的代码。我需要一个解决方案来上传多个文件使用webview,这将适用
public class ChromeClient extends WebChromeClient {
// For Android 5.0
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
contentSelectionIntent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
contentSelectionIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri[]> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri[]> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri[]> uploadMsg) {
openFileChooser(uploadMsg, "");
}
}
公共类ChromeClient扩展WebChromeClient{
//适用于Android 5.0
公共布尔onShowFileChooser(WebView视图、ValueCallback文件路径、WebChromeClient.FileChooseParams文件选择器参数){
//再次检查我们是否没有任何现有回调
if(mFilePathCallback!=null){
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback=文件路径;
Intent takePictureIntent=新的意图(MediaStore.ACTION\u IMAGE\u CAPTURE);
if(takePictureContent.resolveActivity(getPackageManager())!=null){
//创建照片应该放在哪里的文件
文件photoFile=null;
试一试{
photoFile=createImageFile();
takePictureContent.putExtra(“光路”,mCameraPhotoPath);
}捕获(IOEX异常){
//创建文件时出错
Log.e(标记“无法创建图像文件”,例如);
}
//仅当成功创建文件时才继续
if(photoFile!=null){
mCameraPhotoPath=“文件:”+photoFile.getAbsolutePath();
takePictureContent.putExtra(MediaStore.EXTRA_输出,
fromFile(photoFile));
}否则{
takePictureContent=null;
}
}
意向内容选择内容=新意向(意向.行动\打开\文档);
contentSelectionContent.putExtra(Intent.EXTRA\u允许\u倍数,true);
ContentSelectionContent.addFlags(Intent.FLAG\u授予\u持久性\u URI\u权限);
ContentSelectionContent.addFlags(Intent.FLAG\u授予\u读取\u URI\u权限);
ContentSelectionContent.addCategory(Intent.CATEGORY\u可打开);
contentSelectionContent.setType(“image/*”);
意图[]意图射线;
if(takePictureContent!=null){
intentArray=newintent[]{takePictureIntent};
}否则{
intentArray=新意图[0];
}
意图选择器content=新意图(Intent.ACTION\u选择器);
选择content.putExtra(Intent.EXTRA\u Intent,content selection内容);
选择content.putExtra(Intent.EXTRA_标题,“图像选择器”);
选择content.putExtra(Intent.EXTRA\u INITIAL\u INTENTS,intentArray);
startActivityForResult(选择内容、输入文件、请求代码);
返回true;
}
//其他Android版本的openFileChooser
public void openFileChooser(ValueCallback uploadMsg、字符串接受类型、字符串捕获){
openFileChooser(uploadMsg,acceptType);
}
//适用于Android 3.0的openFileChooser+
public void openFileChooser(ValueCallback uploadMsg,String acceptType){
mUploadMessage=上传消息;
//在SD卡上创建AndroidExample文件夹
//在SD卡上创建AndroidExample文件夹
File imageStorageDir=新文件(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY\u图片)
,“AndroidExampleFolder”);
如果(!imageStorageDir.exists()){
//在SD卡上创建AndroidExample文件夹
imageStorageDir.mkdirs();
}
//创建相机捕获的图像文件路径和名称
文件=新文件(
imageStorageDir+File.separator+“IMG\ux”
+String.valueOf(System.currentTimeMillis())
+“.jpg”);
mCapturedImageURI=Uri.fromFile(文件);
//摄像机捕捉图像意图
最终意图捕获意图=新意图(android.provider.MediaStore.ACTION\u IMAGE\u CAPTURE);
putExtra(MediaStore.EXTRA_输出,mCapturedImageURI);
意向i=新意向(意向.行动\u获取\u内容);
i、 putExtra(Intent.EXTRA_允许_倍数,true);
i、 addCategory(意图。类别可打开);
i、 setType(“image/*”);
//创建文件选择器意图
Intent chooserint=Intent.createChooser(i,“图像选择器”);
//将摄影机意图设置为文件选择器
选择content.putExtra(Intent.EXTRA_INITIAL_INTENTS,新包裹[]{captureentent});
//在选择映像时调用ActivityResult活动方法
startActivityForResult(选择内容、文件选择器\u结果代码);
}
//适用于Android<3.0的openFileChooser
public void openFileChooser(ValueCallback uploadMsg){
openFileChooser(uploadMsg,“”);
}
}
这是onActivityResult代码
@覆盖
ActivityResult上的公共void(int请求代码、int结果代码、意图数据){
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.LOLLIPOP){
if(requestCode!=输入_文件_请求_代码| | mFilePathCallback==null){
super.onActivityResult(请求代码、结果代码、数据);
返回;
}
Uri[]results=null;
//检查响应是否良好
if(resultCode==Activity.RESULT\u确定){
如果(数据==null){
//如果没有数据,那么我们可能已经拍了一张照片
if(mCameraPhotoPath!=null){
结果=新Uri[]{Uri.parse(mCameraPhotoPath)};
}
}否则{
if(data.getData()!=null){
字符串dataString=data.getDataString();
if(数据字符串!=null){
//结果=新Uri[]
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
if (data.getData() != null) {
String dataString = data.getDataString();
if (dataString != null) {
// results = new Uri[]{Uri.parse(dataString)};
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(Uri.parse(dataString.replace("%3A", ":")));
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String type = wholeID.split(":")[0];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
results = new Uri[]{Uri.parse("file:" + filePath)};
}
cursor.close();
}
} else {
if (data.getClipData() != null) {
ClipData clipData = data.getClipData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
results = new Uri[clipData.getItemCount()];
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item image = clipData.getItemAt(i);
Uri uri = image.getUri();
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String type = wholeID.split(":")[0];
String contentUri;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.DATA;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.DATA;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.DATA;
}
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
results[i] = Uri.parse("file:" + filePath);
}
}
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result[] = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
if (data.getData() != null)
result[0] = data.getData();
else {
if (data.getClipData() != null) {
result = new Uri[data.getClipData().getItemCount()];
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
result[i] = data.getClipData().getItemAt(i).getUri();
}
} else {
result = null;
}
}
// retrieve from the private variable if the intent is null
//result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}