Android WebView 上传图片文件有坑

转自:http://blog.csdn.net/dsb2008dsb/article/details/71713465

首先说下这个坑是怎么来的,本来要在项目中集成一个第三方提供的功能,但是第三方没有SDK,只给了个H5的页面,只能用webview给套进去了,本来以为事情很简单,分分钟的事情,可是页面里面竟然有图片上传的功能,这也没啥,网上找了段代码加上就OK了,可是本人的手机就是掉不起来文件选择对话框,谷歌和百度一番之后,坑出现了,并且对我这个情况无解,那就是安卓版本4.4、4.4.1、4.4.2这几个版本不被支持,除非H5是自己写的,可以Cordova实现,挖坑的就是谷歌这货自己。谁看到了这个文章,并且有解决办法,可以回复我,本人感激不尽。最后,上点源码,调试过的,谁想用可以直接拿去(包含了cookie处理),但是记得判断安卓版本号,源码如下:

[java]  view plain  copy
  1. public class KengActivity extends BaseActivity implements View.OnClickListener {  
  2.   
  3.     private WebView webView;  
  4.     private ImageView ivBack;  
  5.     private String url;  
  6.   
  7.     public final static int FILECHOOSER_RESULTCODE = 1;  
  8.     public final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 2;  
  9.     public ValueCallback mUploadMessage;  
  10.     public ValueCallback mUploadMessageForAndroid5;  
  11.   
  12.     @Override  
  13.     public void onCreateActivity() {  
  14.         setContentView(R.layout.activity_lanjingling_pay);  
  15.     }  
  16.   
  17.     @Override  
  18.     protected void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         EventBus.getDefault().register(this);  
  21.         url = getIntent().getExtras().getString("url");  
  22.         initView();  
  23.         initData();  
  24.     }  
  25.   
  26.     private void initView() {  
  27.         webView = (WebView) findViewById(R.id.webView);  
  28.         ivBack = (ImageView) findViewById(R.id.ivBack);  
  29.     }  
  30.   
  31.     private void initData() {  
  32.   
  33.         WebSettings webViewSettings = webView.getSettings();  
  34.         webViewSettings.setJavaScriptEnabled(true);  
  35.         webViewSettings.setSupportZoom(false);  
  36.         webViewSettings.setBuiltInZoomControls(false);  
  37.         webViewSettings.setAppCacheEnabled(false);  
  38.         webViewSettings.setLoadWithOverviewMode(true);  
  39.         webView.canGoBack();  
  40.         webView.setWebChromeClient(new MyWebChromeClient());  
  41.         /** 
  42.          * 设置webview支持https 
  43.          */  
  44.         webView.setWebViewClient(new WebViewClient() {  
  45.             public boolean shouldOverrideUrlLoading(WebView view, String url) {  
  46.                 return super.shouldOverrideUrlLoading(view, url);  
  47.             }  
  48.   
  49.             @Override  
  50.             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {  
  51.                 handler.proceed();  
  52.             }  
  53.         });  
  54.   
  55.         /** 
  56.          *  给webview跳转的url添加cookie 
  57.          */  
  58.         CookieSyncManager.createInstance(context);  
  59.         CookieManager cookieManager = CookieManager.getInstance();  
  60.         cookieManager.setAcceptCookie(true);  
  61.   
  62.         PersistentCookieStore myCookieStore = new PersistentCookieStore(context);  
  63.         List cookies = myCookieStore.getCookies();  
  64.         for (int i = 0; i < cookies.size(); i++) {  
  65.             HttpCookie httpCookie = cookies.get(i);  
  66.             if (httpCookie.getName().equals("PHPSESSID")) {  
  67.                 cookieManager.setCookie(url, httpCookie.getName() + "=" + httpCookie.getValue());  
  68.             }  
  69.         }  
  70.         CookieSyncManager.getInstance().sync();  
  71.         webView.loadUrl(url);  
  72.         LoadingDialog.showProgressDialog(context);  
  73.     }  
  74.   
  75.   
  76.     private class MyWebChromeClient extends WebChromeClient {  
  77.         @Override  
  78.         public void onProgressChanged(WebView view, int newProgress) {  
  79.             if (newProgress == 100) {  
  80.                 LoadingDialog.closeProgressDialog();  
  81.             }  
  82.             super.onProgressChanged(view, newProgress);  
  83.         }  
  84.   
  85.         public void openFileChooser(ValueCallback uploadMsg) {  
  86.   
  87.             mUploadMessage = uploadMsg;  
  88.             Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
  89.             i.addCategory(Intent.CATEGORY_OPENABLE);  
  90.             i.setType("image/*");  
  91.             KengActivity.this.startActivityForResult(  
  92.                     Intent.createChooser(i, "File Chooser"),  
  93.                     FILECHOOSER_RESULTCODE);  
  94.   
  95.         }  
  96.   
  97.         public void openFileChooser(ValueCallback uploadMsg,  
  98.                                     String acceptType) {  
  99.             mUploadMessage = uploadMsg;  
  100.             Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
  101.             i.addCategory(Intent.CATEGORY_OPENABLE);  
  102.             i.setType("*/*");  
  103.             KengActivity.this.startActivityForResult(  
  104.                     Intent.createChooser(i, "File Browser"),  
  105.                     FILECHOOSER_RESULTCODE);  
  106.         }  
  107.   
  108.         // For Android 4.1  
  109.         public void openFileChooser(ValueCallback uploadMsg,  
  110.                                     String acceptType, String capture) {  
  111.             mUploadMessage = uploadMsg;  
  112.             Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
  113.             i.addCategory(Intent.CATEGORY_OPENABLE);  
  114.             i.setType("image/*");  
  115.             KengActivity.this.startActivityForResult(  
  116.                     Intent.createChooser(i, "File Chooser"),  
  117.                     FILECHOOSER_RESULTCODE);  
  118.   
  119.         }  
  120.   
  121.         @Override  
  122.         public boolean onShowFileChooser(WebView webView,  
  123.                                          ValueCallback filePathCallback,  
  124.                                          FileChooserParams fileChooserParams) {  
  125.             openFileChooserImplForAndroid5(filePathCallback);  
  126.             return true;//重要,没有这个会报错  
  127.         }  
  128.     }  
  129.   
  130.     private void openFileChooserImplForAndroid5(ValueCallback uploadMsg) {  
  131.         mUploadMessageForAndroid5 = uploadMsg;  
  132.         Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);  
  133.         contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);  
  134.         contentSelectionIntent.setType("image/*");  
  135.         Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);  
  136.         chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);  
  137.         chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");  
  138.         startActivityForResult(chooserIntent,  
  139.                 FILECHOOSER_RESULTCODE_FOR_ANDROID_5);  
  140.     }  
  141.   
  142.     @Override  
  143.     protected void onActivityResult(int requestCode, int resultCode,Intent intent) {  
  144.   
  145.         if (requestCode == FILECHOOSER_RESULTCODE) {  
  146.             if (null == mUploadMessage)  
  147.                 return;  
  148.             Uri result = intent == null || resultCode != RESULT_OK ? null: intent.getData();  
  149.             if (result == null) {  
  150.                 mUploadMessage.onReceiveValue(result);  
  151.                 mUploadMessage = null;  
  152.                 return;  
  153.             }  
  154.   
  155.             Bitmap bm = null;  
  156.             //外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口  
  157.             ContentResolver resolver = getContentResolver();  
  158.             try {  
  159.                 Uri originalUri = intent.getData(); // 获得图片的uri  
  160.                 bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);  
  161.                 // 这里开始的第二部分,获取图片的路径:  
  162.                 String[] proj = {MediaStore.Images.Media.DATA};  
  163.                 // 好像是android多媒体数据库的封装接口,具体的看Android文档  
  164.                 Cursor cursor = managedQuery(originalUri, proj, nullnull,null);  
  165.                 // 按我个人理解 这个是获得用户选择的图片的索引值  
  166.                 int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
  167.                 // 将光标移至开头 ,这个很重要,不小心很容易引起越界  
  168.                 cursor.moveToFirst();  
  169.                 // 最后根据索引值获取图片路径  
  170.                 String path = cursor.getString(column_index);  
  171.                 Uri uri = Uri.fromFile(new File(path));  
  172.                 mUploadMessage.onReceiveValue(uri);  
  173.             } catch (IOException e) {  
  174.                 Log.e("TAG-->Error", e.toString());  
  175.             }  
  176.         } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {  
  177.             if (null == mUploadMessageForAndroid5)  
  178.                 return;  
  179.             Uri result = (intent == null || resultCode != RESULT_OK) ? null: intent.getData();              
  180.             if (result != null) {  
  181.                 mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});  
  182.             } else {  
  183.                 mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});  
  184.             }  
  185.             mUploadMessageForAndroid5 = null;  
  186.         }  
  187.     }  
  188. }  

你可能感兴趣的:(Android)