weex android 选择文件 拍照 获得uri 并转为文件真实路径 转base64码 回传weex

  1. public class findModule extends WXModule {
        /**
         * 打开本地文件器
         */
        JSCallback callback;

        @JSMethod(uiThread = true)
        public void openPdf(final JSCallback callback) {
            openFileSelector();
            findModule.this.callback = callback;
        }

        public void openFileSelector() {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");//设置类型,我这里是任意类型,任意后缀的可以这样写。
    //      intent.setType("application/pdf");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            ((Activity) (mWXSDKInstance.getContext())).startActivityForResult(intent, 0);
        }

        @Override

        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
                    Uri url = data.getData();
    //                String[] filePathColumns = {MediaStore.Images.Media.DATA};
    //                Cursor c = mWXSDKInstance.getContext().getContentResolver().query(url, null, null, null, null);
    //                c.moveToFirst();
    //               System.out.println(c );
    //                String v_file = c.getString(0);// 图片文件路径
    //                String v_path = c.getString(1);
    //                String v_size = c.getString(2); // 图片大小
    //                String v_name = c.getString(3); // 图片文件名
    //                String v_other = c.getString(4); // 图片文件名
    //                String picturePath = c.getString(columnIndex);
    //                c.close();
    //   红色部分    这里是安卓系统4.4之前 uri 转 文件路径的老方法 


    weex android 选择文件 拍照 获得uri 并转为文件真实路径 转base64码 回传weex

    //   -------------------------- 这里很重要  -------------------------------------
            String v_path  = getPathByUri4kitkat(mWXSDKInstance.getContext(),url);
    //   -------------------------- 这里很重要 -------------------------------------
    //      getPathByUri4kitkat 这个方法 适合4.4 系统后 uri 转file路径

                    System.out.println(v_path );
                    onResult(v_path);
            }
        }
    // -------------------------- 结果回调 -------------------------------------
        public void onResult(String url ) {
            if (url== null)
                return;

            System.out.println(url);
            File file = new File(url);
            String base64=  fileToBase64(file);
            System.out.println(base64);
            HashMap m = new HashMap();
            m.put("path", "sdcard:" + base64);
            callback.invoke(m);
        }
    // -------------------------- file 文件路径转base64码 -------------------------------------
        private String fileBase64String(String path) {
            try {
                FileInputStream fis = new FileInputStream(path);//转换成输入流
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = fis.read(buffer)) >= 0) {
                    baos.write(buffer, 0, count);//读取输入流并写入输出字节流中
                }
                fis.close();//关闭文件输入流
                String uploadBuffer = new String(Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT));  //进行Base64编码
                return uploadBuffer;
            } catch (Exception e) {
                return null;
            }
        }

        /**
         * 文件转base64字符串
         *
         * @param file
         * @return
         */
        public String fileToBase64(File file) {
            String base64 = null;
            InputStream in = null;
            try {
                in = new FileInputStream(file);
                byte[] bytes = new byte[in.available()];
                int length = in.read(bytes);
                base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return base64;
        }
    // -------------- 重点部分的函数 uri 转 file 真实路径 ----------------------------------
    //获得路径长什么样子呢
    // 示列

    //  /storage/emulated/0/Pictures/image-13fc2022-4a2c-45be-a79a-976a9812919e4449211495266290891.jpg
    weex android 选择文件 拍照 获得uri 并转为文件真实路径 转base64码 回传weex
        // 专为Android4.4设计的从Uri获取文件绝对路径,以前的方法已不好使
        @SuppressLint("NewApi")
        public  String
    getPathByUri4kitkat(final Context context, final Uri uri) {
            final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
            // DocumentProvider
            if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
                if (isExternalStorageDocument(uri)) {// ExternalStorageProvider
                    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];
                    }
                } else if (isDownloadsDocument(uri)) {// DownloadsProvider
                    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);
                } else if (isMediaDocument(uri)) {// MediaProvider
                    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);
                }
            } else if ("content".equalsIgnoreCase(uri.getScheme())) {// MediaStore
                // (and
                // general)
                return getDataColumn(context, uri, null, null);
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {// File
                return uri.getPath();
            }
            return null;
        }

        /**
         * 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  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;
        }

        /**
         * @param uri
         *            The Uri to check.
         * @return Whether the Uri authority is ExternalStorageProvider.
         */
        public  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  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  boolean isMediaDocument(Uri uri) {
            return "com.android.providers.media.documents".equals(uri.getAuthority());
        }



    //--------------------------------------------------------------------------------
    // -----4.4之前的uri 转 file路径方法 高版本转出来路径为nul  本人开始debug 多次搞得怀疑-------------------------------




    //    public  String getPath(final Uri uri) {
    //        if (null == uri)
    //            return null;
    //        final String scheme = uri.getScheme();
    //        String data = null;
    //        if (scheme == null)
    //            data = uri.getPath();
    //        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
    //            data = uri.getPath();
    //        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
    //            Cursor cursor = mWXSDKInstance.getContext().getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
    //            if (null != cursor) {
    //                if (cursor.moveToFirst()) {
    //                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
    //                    if (index > -1) {
    //                        data = cursor.getString(index);
    //                    }
    //                }
    //                cursor.close();
    //            }
    //        }
    //        return data;
    //    }
    }

// 下面是我 debug  获得的 data 为null   

weex android 选择文件 拍照 获得uri 并转为文件真实路径 转base64码 回传weex

//检查 自己的模拟器的系统

weex android 选择文件 拍照 获得uri 并转为文件真实路径 转base64码 回传weex

//发现 系统的级别高    果断  换函数   getPathByUri4kitkat