Android 解决WebView无法上传文件的问题
Android解决WebView无法上传文件的问题
Android原生的WebView并不支持上传文件,需要我们自己实现相应的方法。于是我把工作中的相关代码记录下来。下次直接拿来用就行了。一点一滴都是经验。
1。需要定义三个变量
privateValueCallbackuploadMessageAboveL; privatefinalstaticintFILE_CHOOSER_RESULT_CODE=10000; privateValueCallback uploadMessage;
2.重写Activity相关方法
privatevoidopenImageChooserActivity(){
Intenti=newIntent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i,"ImageChooser"),FILE_CHOOSER_RESULT_CODE);
}
@Override
protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
super.onActivityResult(requestCode,resultCode,data);
if(requestCode==FILE_CHOOSER_RESULT_CODE){
if(null==uploadMessage&&null==uploadMessageAboveL)return;
Uriresult=data==null||resultCode!=RESULT_OK?null:data.getData();
if(uploadMessageAboveL!=null){
onActivityResultAboveL(requestCode,resultCode,data);
}elseif(uploadMessage!=null){
uploadMessage.onReceiveValue(result);
uploadMessage=null;
}
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
privatevoidonActivityResultAboveL(intrequestCode,intresultCode,Intentintent){
if(requestCode!=FILE_CHOOSER_RESULT_CODE||uploadMessageAboveL==null)
return;
Uri[]results=null;
if(resultCode==Activity.RESULT_OK){
if(intent!=null){
StringdataString=intent.getDataString();
ClipDataclipData=intent.getClipData();
if(clipData!=null){
results=newUri[clipData.getItemCount()];
for(inti=0;i
3.重写WebChromeClient中的相关方法
//ForAndroid<3.0
publicvoidopenFileChooser(ValueCallbackvalueCallback){
uploadMessage=valueCallback;
openImageChooserActivity();
}
//ForAndroid>=3.0
publicvoidopenFileChooser(ValueCallbackvalueCallback,StringacceptType){
uploadMessage=valueCallback;
openImageChooserActivity();
}
//ForAndroid>=4.1
publicvoidopenFileChooser(ValueCallbackvalueCallback,StringacceptType,Stringcapture){
uploadMessage=valueCallback;
openImageChooserActivity();
}
//ForAndroid>=5.0
@Override
publicbooleanonShowFileChooser(WebViewwebView,ValueCallbackfilePathCallback,WebChromeClient.FileChooserParamsfileChooserParams){
uploadMessageAboveL=filePathCallback;
openImageChooserActivity();
returntrue;
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!