在Android浏览器中通过WebView调用相机拍照/选择文件 上传到服务器

最近做的一个项目中,有这样一个要求,在浏览器中调用系统的拍照功能或者选择文件,然后将文件上传到服务器,类似修改头像。        简单而言,就是在一个html页面中有这样一段代码 <input class="filePrew" type="file" capture="camera" accept="image/*" name="image">



刚开始的时候,没有感觉很难的,因为在UC浏览器、系统自带的浏览器中都可以进行拍照/文件管理器选择,可是在自己所写的Activity中却不行。后来实在是没有思路了,就在网上找了一下,发现要        实现这种功能,都是在webview的WebChromeClient中覆盖掉openFileChooser方法,注意openFileChooser方法在WebChromeClient中有@hide标记。这里只管重写即可,下面将主要代码贴出来,做个记录        

[java]  view plain copy
  1. private ValueCallback<Uri> mUploadFile;  
  2.     /**拍照/选择文件请求码*/  
  3.     private static final int REQUEST_UPLOAD_FILE_CODE = 12343;  
  4.     private void setWebChromeClient()  
  5.     {  
  6.         if (null != mMainWebView)  
  7.         {  
  8.             mMainWebView.setWebChromeClient(new WebChromeClient()  
  9.             {  
  10.                 // Andorid 4.1+  
  11.                 public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture)  
  12.                 {  
  13.                     openFileChooser(uploadFile);  
  14.                 }  
  15.   
  16.                 // Andorid 3.0 +  
  17.                 public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType)  
  18.                 {  
  19.                     openFileChooser(uploadFile);  
  20.                 }  
  21.   
  22.                 // Android 3.0  
  23.                 public void openFileChooser(ValueCallback<Uri> uploadFile)  
  24.                 {  
  25.                     // Toast.makeText(WebviewActivity.this, "上传文件/图片",Toast.LENGTH_SHORT).show();  
  26.                     mUploadFile = uploadFile;  
  27.                     startActivityForResult(Intent.createChooser(createCameraIntent(), "Image Browser"), REQUEST_UPLOAD_FILE_CODE);  
  28.                 }  
  29.             });  
  30.         }  
  31.     }  
  32.   
  33.     private Intent createCameraIntent()  
  34.     {  
  35.         Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//拍照  
  36.         //=======================================================  
  37.         Intent imageIntent = new Intent(Intent.ACTION_GET_CONTENT);//选择图片文件  
  38.         imageIntent.setType("image/*");  
  39.         //=======================================================  
  40.         return cameraIntent;  
  41.     }  
  42.     //最后在OnActivityResult中接受返回的结果  
  43.     protected void onActivityResult(int requestCode, int resultCode, Intent data)  
  44.     {  
  45.         if (requestCode == REQUEST_UPLOAD_FILE_CODE && resultCode == RESULT_OK)  
  46.         {  
  47.             if (null == mUploadFile)  
  48.             {  
  49.                 return;  
  50.             }  
  51.             Uri result = (null == data) ? null : data.getData();  
  52.             if (null != result)  
  53.             {  
  54.                 ContentResolver resolver = this.getContentResolver();  
  55.                 String[] columns = { MediaStore.Images.Media.DATA };  
  56.                 Cursor cursor = resolver.query(result, columns, nullnullnull);  
  57.                 cursor.moveToFirst();  
  58.                 int columnIndex = cursor.getColumnIndex(columns[0]);  
  59.                 String imgPath = cursor.getString(columnIndex);  
  60.                 System.out.println("imgPath = " + imgPath);  
  61.                 if (null == imgPath)  
  62.                 {  
  63.                     return;  
  64.                 }  
  65.                 File file = new File(imgPath);  
  66.                    //将图片处理成大小符合要求的文件  
  67.                 result = Uri.fromFile(handleFile(file));  
  68.                 mUploadFile.onReceiveValue(result);  
  69.                 mUploadFile = null;       
  70.             }  
  71.         }  
  72.         super.onActivityResult(requestCode, resultCode, data);  
  73.     }  
  74.     /**处理拍照/选择的文件*/  
  75.     private File handleFile(File file)  
  76.     {  
  77.         DisplayMetrics dMetrics = getResources().getDisplayMetrics();  
  78.         BitmapFactory.Options options = new Options();  
  79.         options.inJustDecodeBounds = true;  
  80.          BitmapFactory.decodeFile(file.getAbsolutePath(), options);  
  81.         int imageWidth = options.outWidth;  
  82.         int imageHeight = options.outHeight;  
  83.         System.out.println("  imageWidth = " + imageWidth + " imageHeight = " + imageHeight);  
  84.         int widthSample = (int) (imageWidth / (dMetrics.density * 90));  
  85.         int heightSample = (int) (imageHeight / (dMetrics.density * 90));  
  86.         System.out.println("widthSample = " + widthSample + " heightSample = " + heightSample);  
  87.         options.inSampleSize = widthSample < heightSample ? heightSample : widthSample;  
  88.         options.inJustDecodeBounds = false;  
  89.         Bitmap newBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);  
  90.         System.out.println("newBitmap.size = " + newBitmap.getRowBytes() * newBitmap.getHeight());  
  91.         File handleFile = new File(file.getParentFile(), "upload.png");  
  92.         try  
  93.         {  
  94.             if (newBitmap.compress(CompressFormat.PNG, 50new FileOutputStream(handleFile)))  
  95.             {  
  96.                 System.out.println("保存图片成功");  
  97.             }  
  98.         }  
  99.         catch (FileNotFoundException e)  
  100.         {  
  101.             e.printStackTrace();  
  102.         }  
  103.   
  104.         return handleFile;  
  105.   
  106.     }  


  这样就可以在WebView中上传文件了。记得要添加相应的权限!  
       参考:http://developer.android.com/about/versions/android-3.0.html

  http://blog.sina.com.cn/s/blog_5749ead90101clrn.html  


  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要实现网页通过 WebView 调用 Android 的图片或文件选择,可以使用以下步骤: 1.在 Android 代码,为 WebView 设置 WebChromeClient,并重写 onShowFileChooser 方法。 2.在 onShowFileChooser 方法调用系统的文件选择器或图库,让用户选择要上传的文件或图片。 3.将用户选择文件或图片返回给 WebView,并在 JavaScript 处理上传操作。 下面是实现步骤的示例代码: 1.在 Android 代码,为 WebView 设置 WebChromeClient,并重写 onShowFileChooser 方法。 ```java webView.setWebChromeClient(new WebChromeClient() { @Override public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { // 在这里调用系统的文件选择器或图库,让用户选择要上传的文件或图片 return true; } }); ``` 2.在 onShowFileChooser 方法调用系统的文件选择器或图库,让用户选择要上传的文件或图片。 ```java @Override public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Intent intent = fileChooserParams.createIntent(); try { startActivityForResult(intent, REQUEST_CODE_UPLOAD_FILE); } catch (ActivityNotFoundException e) { e.printStackTrace(); } } return true; } ``` 3.将用户选择文件或图片返回给 WebView,并在 JavaScript 处理上传操作。 ```java @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE_UPLOAD_FILE && resultCode == RESULT_OK) { Uri[] uris = new Uri[1]; uris[0] = data.getData(); if (mFilePathCallback != null) { mFilePathCallback.onReceiveValue(uris); } } } ``` 在 JavaScript ,可以通过监听 input[type=file] 的 change 事件,获取用户选择文件或图片。 ```javascript var fileInput = document.createElement('input'); fileInput.type = 'file'; fileInput.onchange = function() { var file = fileInput.files[0]; // 处理上传操作 }; fileInput.click(); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值