web页面中input type="file"的事件监听在webview中使用onShowFileChooser实现,代码如下:                                                                                                     
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends Activity {private static final int INPUT_FILE_REQUEST_CODE = 1;
    private static final String TAG = MainActivity.class.getSimpleName();
    private WebView webView;
    private WebSettings webSettings;
    private ValueCallback<Uri[]> mUploadMessage;
    private String mCameraPhotoPath = null;
    private long size = 0;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {if (requestCode != INPUT_FILE_REQUEST_CODE || mUploadMessage == null) {super.onActivityResult(requestCode, resultCode, data);
            return;
        }try {String file_path = mCameraPhotoPath.replace("file:","");
            File file = new File(file_path);
            size = file.length();

        }catch (Exception e){Log.e("Error!", "Error while opening image file" + e.getLocalizedMessage());
        }if (data != null || mCameraPhotoPath != null) {Integer count = 1;
            ClipData images = null;
            try {images = data.getClipData();
            }catch (Exception e) {Log.e("Error!", e.getLocalizedMessage());
            }if (images == null && data != null && data.getDataString() != null) {count = data.getDataString().length();
            } else if (images != null) {count = images.getItemCount();
            }Uri[] results = new Uri[count];
            // Check that the response is a good one
            if (resultCode == Activity.RESULT_OK) {if (size != 0) {// If there is not data, then we may have taken a photo
                    if (mCameraPhotoPath != null) {results = new Uri[]{Uri.parse(mCameraPhotoPath)};
                    }} else if (data.getClipData() == null) {results = new Uri[]{Uri.parse(data.getDataString())};
                } else {for (int i = 0; i < images.getItemCount(); i++) {results[i] = images.getItemAt(i).getUri();
                    }}}mUploadMessage.onReceiveValue(results);
            mUploadMessage = null;
        }}@Override
    protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = (WebView) findViewById(R.id.webView);
        webSettings = webView.getSettings();
        webSettings.setAppCacheEnabled(true);
        webSettings.setCacheMode(webSettings.LOAD_CACHE_ELSE_NETWORK);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setAllowFileAccess(true);
        webView.setWebViewClient(new PQClient());
        webView.setWebChromeClient(new PQChromeClient());
        //if SDK version is greater of 19 then activate hardware acceleration otherwise activate software acceleration
        if (Build.VERSION.SDK_INT >= 19) {webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        } else if (Build.VERSION.SDK_INT >= 11 && Build.VERSION.SDK_INT < 19) {webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }webView.loadUrl("http://10.194.12.80:8088/FAI/SMTvnp.aspx"); //https://en.imgbb.com/
    }private File createImageFile() throws IOException {// Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File imageFile = File.createTempFile(imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        return imageFile;
    }public class PQChromeClient 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 (mUploadMessage != null) {mUploadMessage.onReceiveValue(null);
            }mUploadMessage = filePath;
            Log.e("FileCooserParams => ", filePath.toString());

            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_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {intentArray = new Intent[]{takePictureIntent};
            } else {intentArray = new Intent[2];
            }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(Intent.createChooser(chooserIntent, "Select images"), 1);

            return true;
        }}public boolean onKeyDown(int keyCode, KeyEvent event) {// Check if the key event was the Back button and if there's history
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {webView.goBack();
            return true;
        }// If it wasn't the Back key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)

        return super.onKeyDown(keyCode, event);
    }public class PQClient extends WebViewClient {ProgressDialog progressDialog;

        public boolean shouldOverrideUrlLoading(WebView view, String url) {// If url contains mailto link then open Mail Intent
            if (url.contains("mailto:")) {// Could be cleverer and use a regex
                //Open links in new browser
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

                // Here we can open new activity

                return true;

            } else {// Stay within this webview and load url
                view.loadUrl(url);
                return true;
            }}//Show loader on url load
        public void onPageStarted(WebView view, String url, Bitmap favicon) {// Then show progress  Dialog
            // in standard case YourActivity.this
            if (progressDialog == null) {progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setMessage("Loading...");
                progressDialog.hide();
            }}// Called when all page resources loaded
        public void onPageFinished(WebView view, String url) {webView.loadUrl("javascript:(function(){ " +"document.getElementById('android-app').style.display='none';})()");

            try {// Close progressDialog
                if (progressDialog.isShowing()) {progressDialog.dismiss();
                    progressDialog = null;
                }} catch (Exception exception) {exception.printStackTrace();
            }}}}

webview开发中使用onShowFileChooser实现web页打开照相机或者图片浏览相关推荐

  1. iOS开发中UIImageView逆时针旋转,并得到旋转后的图片

    很多小伙伴会用系统的动画旋转,但都是顺时针的,但是开发中有些场景需要用到逆时针旋转效果更好,比方说tableView的 展开/收起 指示箭头方向的变换,如果是顺时针复位,就会显得特别别扭.以下一段代码 ...

  2. iOS开发中,通过URL地址获取网络上的图片

    在iOS开发中,我们有时会通过图片的URL地址来获取网上的图片,下面是一个方法实现: /** 通过URL地址从网上获取图片 */ -(UIImage *) getImageFromURL:(NSStr ...

  3. Web开发中软件工程艺术(Web程序员请进来谈谈,特别是有大型门户网站后台开发的程序员)

    近正着手一个大型综合性门户网站后台管理系统(准确说是内容管理系统)设计  与规划,对网站开发技术有一个较深刻的认识.从Internet的出现到现在,WebSite的开发技术有4个过程:        ...

  4. oracle ERP凭证打印样式,Oracle ERP二次开发中特色鲜明的Web打印模式设计与实现

    0背景随着宽带网络的普及和推广,基于浏览器的B/S结构的应用程序越来越多,客户端免安装.免配置.免维护.免升级;服务器端则采用多层模式,将表示层.商业逻辑层和数据层分开,极大的提髙了开发的效率和数据的 ...

  5. xxs漏洞危害_PHP开发中经常遇到的Web安全漏洞防御详解

    程序员需要掌握基本的web安全知识,防患于未然,你们知道有多少种web安全漏洞吗?这里不妨列举10项吧,你们可以自己去网站找相应的教程来提升自己的1.命令注入(Command Injection)2. ...

  6. ActiveX技术在WEB页上的应用[转载]

       ActiveX技术在WEB页上的应用 汪涛 Internet 的发展可以说是日新月异,这种快速的发展给人们带来了大量的机会.全世界的电信服务商都在寻找增强Internet在线服务的方法.在Int ...

  7. iPhone开发中的技巧整理(四)

    iphone开发笔记 退回输入键盘 - (BOOL) textFieldShouldReturn:(id)textField{ [textField  resignFirstResponder]; } ...

  8. web前端开发论文写作_2019学习Web开发指南

    这是一个2019年你成为前端,后端或全栈开发者的进阶指南: 你不需要学习所有的技术成为一个web开发者 这个指南只是通过简单分类列出了技术选项 我将从我的经验和参考中给出建议 1.基础前端开发者 1. ...

  9. iphone iPhone开发中为UINavigationBar设置背景图片方法

    1:原文摘自:http://mobile.51cto.com/iphone-284865.htm iPhone开发中为UINavigationBar设置背景图片方法是本文要介绍的内容,在iPhone开 ...

最新文章

  1. 安卓高手之路之图形系统【5】安卓ListView和EditText配合使用时的注意事项。
  2. Spring.Net官网翻译
  3. 服务器端 python pdb 调试
  4. 一个几何级数的无限和思考
  5. linux awk入门,awk入门应用
  6. lucene简单实例
  7. 7-Spring Boot的安全管理
  8. 利用 Python 制作酷炫的飞船大战!|原力计划
  9. Mysql逻辑架构简介
  10. JQuery-UI dialog hide属性的取值范围
  11. PySpark-Recipes : I/O操作(txt, json, hdfs, csv...)
  12. 中国电网计算机面试题目,国家电网面试经验
  13. 天闻角川超人气IP「画猫·雅宋」数字藏品限量开售!
  14. 解决资源监视器不显示的问题。
  15. 经纬财富:宜昌炒白银和炒黄金有什么不同?
  16. 微信小程序:简单计算器
  17. css+html工商银行小项目
  18. Python爬虫任务1
  19. 【方法】如何在PPT文稿中插入Word表格?
  20. Java实现基于朴素贝叶斯的情感词分析

热门文章

  1. redis存储token
  2. mysql索引详讲_SQL优化 MySQL版 - B树索引详讲
  3. jenkins搭建_Docker+Jenkins 搭建多版本php环境
  4. java 方法 示例_Java BigDecimaldividAndRemainder()方法与示例
  5. [附源码]Python计算机毕业设计SSM佳音大学志愿填报系统(程序+LW)
  6. 从高维变换的角度理解神经网络
  7. 陈式太极拳的练习步骤与方法
  8. 螺线管 Solenoid
  9. 省赛一Ballons dfs
  10. 高手的Blog 及ACM 好的网站