在Android中通过WebView调用相机拍照/选择文件

本文介绍如何在Android WebView中实现文件和图片的上传功能。通过重写WebChromeClient的openFileChooser方法,并处理Intent请求与响应,实现了从Android 3.0到4.1不同版本的兼容方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现这种功能,都是在webview的WebChromeClient中覆盖掉openFileChooser方法,注意openFileChooser方法在WebChromeClient中有@hide标记。这里只管重写即可,下面将主要代码贴出来,做个记录

private ValueCallback mUploadFile;
/拍照/选择文件请求码*/
private static final int REQUEST_UPLOAD_FILE_CODE = 12343;
private void setWebChromeClient()
{
if (null != mMainWebView)
{
mMainWebView.setWebChromeClient(new WebChromeClient()
{
// Andorid 4.1+
public void openFileChooser(ValueCallback uploadFile, String acceptType, String capture)
{
openFileChooser(uploadFile);
}

            // Andorid 3.0 +  
            public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType)  
            {  
                openFileChooser(uploadFile);  
            }  

            // Android 3.0  
            public void openFileChooser(ValueCallback<Uri> uploadFile)  
            {  
                // Toast.makeText(WebviewActivity.this, "上传文件/图片",Toast.LENGTH_SHORT).show();  
                mUploadFile = uploadFile;  
                startActivityForResult(Intent.createChooser(createCameraIntent(), "Image Browser"), REQUEST_UPLOAD_FILE_CODE);  
            }  
        });  
    }  
}  

private Intent createCameraIntent()  
{  
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//拍照  
    //=======================================================  
    Intent imageIntent = new Intent(Intent.ACTION_GET_CONTENT);//选择图片文件  
    imageIntent.setType("image/*");  
    //=======================================================  
    return cameraIntent;  
}  
//最后在OnActivityResult中接受返回的结果  
protected void onActivityResult(int requestCode, int resultCode, Intent data)  
{  
    if (requestCode == REQUEST_UPLOAD_FILE_CODE && resultCode == RESULT_OK)  
    {  
        if (null == mUploadFile)  
        {  
            return;  
        }  
        Uri result = (null == data) ? null : data.getData();  
        if (null != result)  
        {  
            ContentResolver resolver = this.getContentResolver();  
            String[] columns = { MediaStore.Images.Media.DATA };  
            Cursor cursor = resolver.query(result, columns, null, null, null);  
            cursor.moveToFirst();  
            int columnIndex = cursor.getColumnIndex(columns[0]);  
            String imgPath = cursor.getString(columnIndex);  
            System.out.println("imgPath = " + imgPath);  
            if (null == imgPath)  
            {  
                return;  
            }  
            File file = new File(imgPath);  
               //将图片处理成大小符合要求的文件  
            result = Uri.fromFile(handleFile(file));  
            mUploadFile.onReceiveValue(result);  
            mUploadFile = null;       
        }  
    }  
    super.onActivityResult(requestCode, resultCode, data);  
}  
/处理拍照/选择的文件*/  
private File handleFile(File file)  
{  
    DisplayMetrics dMetrics = getResources().getDisplayMetrics();  
    BitmapFactory.Options options = new Options();  
    options.inJustDecodeBounds = true;  
     BitmapFactory.decodeFile(file.getAbsolutePath(), options);  
    int imageWidth = options.outWidth;  
    int imageHeight = options.outHeight;  
    System.out.println("  imageWidth = " + imageWidth + " imageHeight = " + imageHeight);  
    int widthSample = (int) (imageWidth / (dMetrics.density * 90));  
    int heightSample = (int) (imageHeight / (dMetrics.density * 90));  
    System.out.println("widthSample = " + widthSample + " heightSample = " + heightSample);  
    options.inSampleSize = widthSample < heightSample ? heightSample : widthSample;  
    options.inJustDecodeBounds = false;  
    Bitmap newBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);  
    System.out.println("newBitmap.size = " + newBitmap.getRowBytes() * newBitmap.getHeight());  
    File handleFile = new File(file.getParentFile(), "upload.png");  
    try  
    {  
        if (newBitmap.compress(CompressFormat.PNG, 50, new FileOutputStream(handleFile)))  
        {  
            System.out.println("保存图片成功");  
        }  
    }  
    catch (FileNotFoundException e)  
    {  
        e.printStackTrace();  
    }  

    return handleFile;  

}  

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值