Android WebView 上传文件支持全解析_Android

默认情况下情况下,使用Android的WebView是不能够支持上传文件的。而这个,也是在我们的前端工程师告知之后才了解的。因为Android的每个版本WebView的实现有差异,因此需要对不同版本去适配。花了一点时间,参考别人的代码,这个问题已经解决,这里把我踩过的坑分享出来。
主要思路是重写WebChromeClient,然后在WebViewActivity中接收选择到的文件Uri,传给页面去上传就可以了。
创建一个WebViewActivity的内部类

public class XHSWebChromeClient extends WebChromeClient {

  // For Android 3.0+
  public void openFileChooser(ValueCallback<Uri> uploadMsg) {
    CLog.i("UPFILE", "in openFile Uri Callback");
    if (mUploadMessage != null) {
      mUploadMessage.onReceiveValue(null);
    }
    mUploadMessage = uploadMsg;
    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    i.addCategory(Intent.CATEGORY_OPENABLE);
    i.setType("*/*");
    startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
  }

  // For Android 3.0+
  public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
    CLog.i("UPFILE", "in openFile Uri Callback has accept Type" + acceptType);
    if (mUploadMessage != null) {
      mUploadMessage.onReceiveValue(null);
    }
    mUploadMessage = uploadMsg;
    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    i.addCategory(Intent.CATEGORY_OPENABLE);
    String type = TextUtils.isEmpty(acceptType) ? "*/*" : acceptType;
    i.setType(type);
    startActivityForResult(Intent.createChooser(i, "File Chooser"),
        FILECHOOSER_RESULTCODE);
  }

  // For Android 4.1
  public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
    CLog.i("UPFILE", "in openFile Uri Callback has accept Type" + acceptType + "has capture" + capture);
    if (mUploadMessage != null) {
      mUploadMessage.onReceiveValue(null);
    }
    mUploadMessage = uploadMsg;
    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    i.addCategory(Intent.CATEGORY_OPENABLE);
    String type = TextUtils.isEmpty(acceptType) ? "*/*" : acceptType;
    i.setType(type);
    startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
  }

//Android 5.0+
  @Override
  @SuppressLint("NewApi")
  public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
    if (mUploadMessage != null) {
      mUploadMessage.onReceiveValue(null);
    }
    CLog.i("UPFILE", "file chooser params:" + fileChooserParams.toString());
    mUploadMessage = filePathCallback;
    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    i.addCategory(Intent.CATEGORY_OPENABLE);
    if (fileChooserParams != null && fileChooserParams.getAcceptTypes() != null
        && fileChooserParams.getAcceptTypes().length > 0) {
      i.setType(fileChooserParams.getAcceptTypes()[0]);
    } else {
      i.setType("*/*");
    }
    startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
    return true;
  }
}

上面openFileChooser是系统未暴露的接口,因此不需要加Override的注解,同时不同版本有不同的参数,其中的参数,第一个ValueCallback用于我们在选择完文件后,接收文件回调到网页内处理,acceptType为接受的文件mime type。在Android 5.0之后,系统提供了onShowFileChooser来让我们实现选择文件的方法,仍然有ValueCallback,在FileChooserParams参数中,同样包括acceptType。我们可以根据acceptType,来打开系统的或者我们自己创建文件选择器。当然如果需要打开相机拍照,也可以自己去使用打开相机拍照的Intent去打开即可。
处理选择的文件
以上是打开响应的选择文件的界面,我们还需要处理接收到文件之后,传给网页来响应。因为我们前面是使用startActivityForResult来打开的选择页面,我们会在onActivityResult中接收到选择的结果。Show code:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if (requestCode == FILECHOOSER_RESULTCODE) {
    if (null == mUploadMessage) return;
    Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
    if (result == null) {
      mUploadMessage.onReceiveValue(null);
      mUploadMessage = null;
      return;
    }
    CLog.i("UPFILE", "onActivityResult" + result.toString());
    String path = FileUtils.getPath(this, result);
    if (TextUtils.isEmpty(path)) {
      mUploadMessage.onReceiveValue(null);
      mUploadMessage = null;
      return;
    }
    Uri uri = Uri.fromFile(new File(path));
    CLog.i("UPFILE", "onActivityResult after parser uri:" + uri.toString());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      mUploadMessage.onReceiveValue(new Uri[]{uri});
    } else {
      mUploadMessage.onReceiveValue(uri);
    }

    mUploadMessage = null;
  }
}

以上代码主要就是调用ValueCallback的onReceiveValue方法,将结果传回web。
注意,其他要说的,重要
由于不同版本的差别,Android 5.0以下的版本,ValueCallback 的onReceiveValue接收的参数类型是Uri, 5.0及以上版本接收的是Uri数组,在传值的时候需要注意。
选择文件会使用系统提供的组件或者其他支持的app,返回的uri有的直接是文件的url,有的是contentprovider的uri,因此我们需要统一处理一下,转成文件的uri,可参考以下代码(获取文件的路径)。
调用getPath可以将Uri转成真实文件的Path,然后可以自己生成文件的Uri

public class FileUtils {
  /**
   * @param uri The Uri to check.
   * @return Whether the Uri authority is ExternalStorageProvider.
   */
  public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
  }

  /**
   * @param uri The Uri to check.
   * @return Whether the Uri authority is DownloadsProvider.
   */
  public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
  }

  /**
   * @param uri The Uri to check.
   * @return Whether the Uri authority is MediaProvider.
   */
  public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
  }

  /**
   * Get the value of the data column for this Uri. This is useful for
   * MediaStore Uris, and other file-based ContentProviders.
   *
   * @param context The context.
   * @param uri The Uri to query.
   * @param selection (Optional) Filter used in the query.
   * @param selectionArgs (Optional) Selection arguments used in the query.
   * @return The value of the _data column, which is typically a file path.
   */
  public static String getDataColumn(Context context, Uri uri, String selection,
                    String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
        column
    };

    try {
      cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
          null);
      if (cursor != null && cursor.moveToFirst()) {
        final int column_index = cursor.getColumnIndexOrThrow(column);
        return cursor.getString(column_index);
      }
    } finally {
      if (cursor != null)
        cursor.close();
    }
    return null;
  }

  /**
   * Get a file path from a Uri. This will get the the path for Storage Access
   * Framework Documents, as well as the _data field for the MediaStore and
   * other file-based ContentProviders.
   *
   * @param context The context.
   * @param uri The Uri to query.
   * @author paulburke
   */
  @SuppressLint("NewApi")
  public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
      // ExternalStorageProvider
      if (isExternalStorageDocument(uri)) {
        final String docId = DocumentsContract.getDocumentId(uri);
        final String[] split = docId.split(":");
        final String type = split[0];

        if ("primary".equalsIgnoreCase(type)) {
          return Environment.getExternalStorageDirectory() + "/" + split[1];
        }

        // TODO handle non-primary volumes
      }
      // DownloadsProvider
      else if (isDownloadsDocument(uri)) {

        final String id = DocumentsContract.getDocumentId(uri);
        final Uri contentUri = ContentUris.withAppendedId(
            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

        return getDataColumn(context, contentUri, null, null);
      }
      // MediaProvider
      else if (isMediaDocument(uri)) {
        final String docId = DocumentsContract.getDocumentId(uri);
        final String[] split = docId.split(":");
        final String type = split[0];

        Uri contentUri = null;
        if ("image".equals(type)) {
          contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else if ("video".equals(type)) {
          contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        } else if ("audio".equals(type)) {
          contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }

        final String selection = "_id=?";
        final String[] selectionArgs = new String[] {
            split[1]
        };

        return getDataColumn(context, contentUri, selection, selectionArgs);
      }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
      return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
      return uri.getPath();
    }

    return null;
  }

}

再有,即使获取的结果为null,也要传给web,即直接调用mUploadMessage.onReceiveValue(null),否则网页会阻塞。
最后,在打release包的时候,因为我们会混淆,要特别设置不要混淆WebChromeClient子类里面的openFileChooser方法,由于不是继承的方法,所以默认会被混淆,然后就无法选择文件了。
就这样吧。
原文地址:http://blog.isming.me/2015/12/21/android-webview-upload-file/

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索android
, webview
上传文件
android webview 上传、webview支持文件上传、webview上传图片、ios webview 上传图片、webview文件上传,以便于您获取更多的相关知识。

时间: 2024-09-10 21:32:04

Android WebView 上传文件支持全解析_Android的相关文章

Android WebView 上传文件支持全解析

默认情况下情况下,使用Android的WebView是不能够支持上传文件的.而这个,也是在我们的前端工程师告知之后才了解的.因为Android的每个版本WebView的实现有差异,因此需要对不同版本去适配.花了一点时间,参考别人的代码,这个问题已经解决,这里把我踩过的坑分享出来. 主要思路是重写WebChromeClient,然后在WebViewActivity中接收选择到的文件Uri,传给页面去上传就可以了. 创建一个WebViewActivity的内部类 public class XHSWe

Android实现上传文件功能的方法_Android

本文所述为一个Android上传文件的源代码,每一步实现过程都备有详尽的注释,思路比较清楚,学习了本例所述上传文件代码之后,你可以应对其它格式文件的上传.实例中主要实现上传文件至Server的方法,允许Input.Output,不使用Cache,使Androiod上传文件变得轻松. 主要功能代码如下: package com.test; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.

android使用webview上传文件(相册和拍照)怎么重新选择图片

问题描述 android使用webview上传文件(相册和拍照)怎么重新选择图片 android使用webview上传文件(相册和拍照),第一次选择图片的时候没问题,但第二次选择图片时不能覆盖第一次选择的图片,还是只能上传第一次选择的图片. 解决方案 http://blog.csdn.net/woshinia/article/details/19030437 解决方案二: 在选完照片后把存图片的把集合清空,然后第二次进来的时候重新赋值了 解决方案三: Android使用WebView从相册/拍照

编码-Android httppost 上传文件 中文乱码

问题描述 Android httppost 上传文件 中文乱码 利用CustomMultipartEntity附加的内容: 按照网上的指示,为httppost设置编码,new FileBody时转码,统统不好使! 真心求助!! 核心代码如下: @Override protected String doInBackground(String... params) { String serverResponse = null; HttpClient httpClient = new DefaultH

Android实现上传文件到服务器实例详解_Android

本实例实现每隔5秒上传一次,通过服务器端获取手机上传过来的文件信息并做相应处理:采用Android+Struts2技术. 一.Android端实现文件上传 1).新建一个Android项目命名为androidUpload,目录结构如下: 2).新建FormFile类,用来封装文件信息 package com.ljq.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundExce

android httpclient 上传文件

public void uploadFileClient() { Toast.makeText(this, "现在已经开始上传了!", Toast.LENGTH_LONG).show(); String targetURL = actionUrl;// 上传指定URL File targetFile = new File(uploadFile);// 指定上传文件 PostMethod filePost = new PostMethod(targetURL); try { // 通过以

Android WebView上实现JavaScript与Java交互_Android

其实webview加载资源的速度并不慢,但是如果资源多了,当然就很慢.图片.css .js .html这些资源每个大概需要10-200ms ,一般都是30ms就ok了.不过webview是必须等到全部资源都完成加载,才会进行渲染的,所以加载的速度很重要!从Google上我们了解到,webview加载页面的顺序是:先加载html,然后从里面解析出css.js文件和页面上的图片资源进行加载.如果webkit的缓存里面有,就不加载.加载完这些资源之后,就进行css的渲染和js的执行.Css的渲染一般不

Android图片上传实现预览效果_Android

首先具体分析一下,实现的功能,其中需求分析是必不可少的,需求.逻辑清除之后,再上手写代码,思路会很清晰. 1.多图上传首先得选择图片(这里项目需求是既可以拍照上传也可以从相册中选择) 2.拍照上传很简单了网上也有很多例子,调用照相机,返回uri,获取图片 3.从相册中选择图片  3.1 获取手机中的所有图片  3.2 将图片存到自定义图片数组中显示  3.3 自定义ViewPager浏览图片 主要的逻辑大体是这样,下面具体看一下实现: 一.首先看一下界面: <com.view.NoScrollG

JavaWeb文件上传与下载功能解析_java

在开发过程中文件的上传下载很常用.这里简单的总结一下: 1.文件上传必须满足的条件: a. 页面表单的method必须是post 因为get传送的数据太小了 b. 页面表单的enctype必须是multipart/form-data类型的 c. 表单中提供上传输入域 代码细节: 客户端表单中:<form enctype="multipart/form-data"/> (如果没有这个属性,则服务端读取的文件路径会因为浏览器的不同而不同) 服务端ServletInputStre