Android WebView 上传文件支持全解析
默认情况下情况下,使用Android的WebView是不能够支持上传文件的。而这个,也是在我们的前端工程师告知之后才了解的。因为Android的每个版本WebView的实现有差异,因此需要对不同版本去适配。花了一点时间,参考别人的代码,这个问题已经解决,这里把我踩过的坑分享出来。
主要思路是重写WebChromeClient,然后在WebViewActivity中接收选择到的文件Uri,传给页面去上传就可以了。
创建一个WebViewActivity的内部类
publicclassXHSWebChromeClientextendsWebChromeClient{
//ForAndroid3.0+
publicvoidopenFileChooser(ValueCallback<Uri>uploadMsg){
CLog.i("UPFILE","inopenFileUriCallback");
if(mUploadMessage!=null){
mUploadMessage.onReceiveValue(null);
}
mUploadMessage=uploadMsg;
Intenti=newIntent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
startActivityForResult(Intent.createChooser(i,"FileChooser"),FILECHOOSER_RESULTCODE);
}
//ForAndroid3.0+
publicvoidopenFileChooser(ValueCallbackuploadMsg,StringacceptType){
CLog.i("UPFILE","inopenFileUriCallbackhasacceptType"+acceptType);
if(mUploadMessage!=null){
mUploadMessage.onReceiveValue(null);
}
mUploadMessage=uploadMsg;
Intenti=newIntent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
Stringtype=TextUtils.isEmpty(acceptType)?"*/*":acceptType;
i.setType(type);
startActivityForResult(Intent.createChooser(i,"FileChooser"),
FILECHOOSER_RESULTCODE);
}
//ForAndroid4.1
publicvoidopenFileChooser(ValueCallback<Uri>uploadMsg,StringacceptType,Stringcapture){
CLog.i("UPFILE","inopenFileUriCallbackhasacceptType"+acceptType+"hascapture"+capture);
if(mUploadMessage!=null){
mUploadMessage.onReceiveValue(null);
}
mUploadMessage=uploadMsg;
Intenti=newIntent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
Stringtype=TextUtils.isEmpty(acceptType)?"*/*":acceptType;
i.setType(type);
startActivityForResult(Intent.createChooser(i,"FileChooser"),FILECHOOSER_RESULTCODE);
}
//Android5.0+
@Override
@SuppressLint("NewApi")
publicbooleanonShowFileChooser(WebViewwebView,ValueCallback<Uri[]>filePathCallback,FileChooserParamsfileChooserParams){
if(mUploadMessage!=null){
mUploadMessage.onReceiveValue(null);
}
CLog.i("UPFILE","filechooserparams:"+fileChooserParams.toString());
mUploadMessage=filePathCallback;
Intenti=newIntent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
if(fileChooserParams!=null&&fileChooserParams.getAcceptTypes()!=null
&&fileChooserParams.getAcceptTypes().length>0){
i.setType(fileChooserParams.getAcceptTypes()[0]);
}else{
i.setType("*/*");
}
startActivityForResult(Intent.createChooser(i,"FileChooser"),FILECHOOSER_RESULTCODE);
returntrue;
}
}
上面openFileChooser是系统未暴露的接口,因此不需要加Override的注解,同时不同版本有不同的参数,其中的参数,第一个ValueCallback用于我们在选择完文件后,接收文件回调到网页内处理,acceptType为接受的文件mimetype。在Android5.0之后,系统提供了onShowFileChooser来让我们实现选择文件的方法,仍然有ValueCallback,在FileChooserParams参数中,同样包括acceptType。我们可以根据acceptType,来打开系统的或者我们自己创建文件选择器。当然如果需要打开相机拍照,也可以自己去使用打开相机拍照的Intent去打开即可。
处理选择的文件
以上是打开响应的选择文件的界面,我们还需要处理接收到文件之后,传给网页来响应。因为我们前面是使用startActivityForResult来打开的选择页面,我们会在onActivityResult中接收到选择的结果。Showcode:
@Override
protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
super.onActivityResult(requestCode,resultCode,data);
if(requestCode==FILECHOOSER_RESULTCODE){
if(null==mUploadMessage)return;
Uriresult=data==null||resultCode!=RESULT_OK?null:data.getData();
if(result==null){
mUploadMessage.onReceiveValue(null);
mUploadMessage=null;
return;
}
CLog.i("UPFILE","onActivityResult"+result.toString());
Stringpath=FileUtils.getPath(this,result);
if(TextUtils.isEmpty(path)){
mUploadMessage.onReceiveValue(null);
mUploadMessage=null;
return;
}
Uriuri=Uri.fromFile(newFile(path));
CLog.i("UPFILE","onActivityResultafterparseruri:"+uri.toString());
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){
mUploadMessage.onReceiveValue(newUri[]{uri});
}else{
mUploadMessage.onReceiveValue(uri);
}
mUploadMessage=null;
}
}
以上代码主要就是调用ValueCallback的onReceiveValue方法,将结果传回web。
注意,其他要说的,重要
由于不同版本的差别,Android5.0以下的版本,ValueCallback的onReceiveValue接收的参数类型是Uri,5.0及以上版本接收的是Uri数组,在传值的时候需要注意。
选择文件会使用系统提供的组件或者其他支持的app,返回的uri有的直接是文件的url,有的是contentprovider的uri,因此我们需要统一处理一下,转成文件的uri,可参考以下代码(获取文件的路径)。
调用getPath可以将Uri转成真实文件的Path,然后可以自己生成文件的Uri
publicclassFileUtils{
/**
*@paramuriTheUritocheck.
*@returnWhethertheUriauthorityisExternalStorageProvider.
*/
publicstaticbooleanisExternalStorageDocument(Uriuri){
return"com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
*@paramuriTheUritocheck.
*@returnWhethertheUriauthorityisDownloadsProvider.
*/
publicstaticbooleanisDownloadsDocument(Uriuri){
return"com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
*@paramuriTheUritocheck.
*@returnWhethertheUriauthorityisMediaProvider.
*/
publicstaticbooleanisMediaDocument(Uriuri){
return"com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
*GetthevalueofthedatacolumnforthisUri.Thisisusefulfor
*MediaStoreUris,andotherfile-basedContentProviders.
*
*@paramcontextThecontext.
*@paramuriTheUritoquery.
*@paramselection(Optional)Filterusedinthequery.
*@paramselectionArgs(Optional)Selectionargumentsusedinthequery.
*@returnThevalueofthe_datacolumn,whichistypicallyafilepath.
*/
publicstaticStringgetDataColumn(Contextcontext,Uriuri,Stringselection,
String[]selectionArgs){
Cursorcursor=null;
finalStringcolumn="_data";
finalString[]projection={
column
};
try{
cursor=context.getContentResolver().query(uri,projection,selection,selectionArgs,
null);
if(cursor!=null&&cursor.moveToFirst()){
finalintcolumn_index=cursor.getColumnIndexOrThrow(column);
returncursor.getString(column_index);
}
}finally{
if(cursor!=null)
cursor.close();
}
returnnull;
}
/**
*GetafilepathfromaUri.ThiswillgetthethepathforStorageAccess
*FrameworkDocuments,aswellasthe_datafieldfortheMediaStoreand
*otherfile-basedContentProviders.
*
*@paramcontextThecontext.
*@paramuriTheUritoquery.
*@authorpaulburke
*/
@SuppressLint("NewApi")
publicstaticStringgetPath(finalContextcontext,finalUriuri){
finalbooleanisKitKat=Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT;
//DocumentProvider
if(isKitKat&&DocumentsContract.isDocumentUri(context,uri)){
//ExternalStorageProvider
if(isExternalStorageDocument(uri)){
finalStringdocId=DocumentsContract.getDocumentId(uri);
finalString[]split=docId.split(":");
finalStringtype=split[0];
if("primary".equalsIgnoreCase(type)){
returnEnvironment.getExternalStorageDirectory()+"/"+split[1];
}
//TODOhandlenon-primaryvolumes
}
//DownloadsProvider
elseif(isDownloadsDocument(uri)){
finalStringid=DocumentsContract.getDocumentId(uri);
finalUricontentUri=ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),Long.valueOf(id));
returngetDataColumn(context,contentUri,null,null);
}
//MediaProvider
elseif(isMediaDocument(uri)){
finalStringdocId=DocumentsContract.getDocumentId(uri);
finalString[]split=docId.split(":");
finalStringtype=split[0];
UricontentUri=null;
if("image".equals(type)){
contentUri=MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}elseif("video".equals(type)){
contentUri=MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}elseif("audio".equals(type)){
contentUri=MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
finalStringselection="_id=?";
finalString[]selectionArgs=newString[]{
split[1]
};
returngetDataColumn(context,contentUri,selection,selectionArgs);
}
}
//MediaStore(andgeneral)
elseif("content".equalsIgnoreCase(uri.getScheme())){
returngetDataColumn(context,uri,null,null);
}
//File
elseif("file".equalsIgnoreCase(uri.getScheme())){
returnuri.getPath();
}
returnnull;
}
}
再有,即使获取的结果为null,也要传给web,即直接调用mUploadMessage.onReceiveValue(null),否则网页会阻塞。
最后,在打release包的时候,因为我们会混淆,要特别设置不要混淆WebChromeClient子类里面的openFileChooser方法,由于不是继承的方法,所以默认会被混淆,然后就无法选择文件了。
就这样吧。
原文地址:http://blog.isming.me/2015/12/21/android-webview-upload-file/
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。