关于react-native-image-picker使用过程中的坑

项目中使用的react-native-image-picker的版本是0.26.10,需要拍照或相册中选一张图片,然后上传。

app通过返回的uri加载图片显示没问题,但是上传图片有问题。
使用的是fetch+FormData的方式。

测试手机系统有 4.4、6.0、8.0。测试结果是4.4和6.0系统手机图片正常上传,8.0手机图片上传失败。

showImagePicker = ()=>{
        ImagePicker.showImagePicker(options, (response) => {
            console.log('Response = ', response);

            if (response.didCancel) {
                console.log('User cancelled image picker');
            }else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
            }else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
            }else {
                let source = { uri: response.uri };
                // You can also display the image using data:
                // let source = { uri: 'data:image/jpeg;base64,' + response.data };
                this.setState({
                    avatarSource: source
                });
            }
        });

    }

通过打印response.uri的值,发现都是file://...。android 7+系统,文件路径换成content://URI试试。

查看源码:

@ReactMethod
public void launchCamera(final ReadableMap options, final Callback callback){
    ...
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
      List<ResolveInfo> resInfoList = reactContext.getPackageManager().queryIntentActivities(cameraIntent, PackageManager.MATCH_DEFAULT_ONLY);
      for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        reactContext.grantUriPermission(packageName, cameraCaptureURI, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
      }
    }
    ...

}

grantUriPermission权限添加,应该是大于android7.0系统才需要,因此屏蔽了上面代码中的if判断及内部代码,直接改成

cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

再查看onActivityResult方法,返回的图片路径是在该方法里面处理的。

@Override
  public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
    ...
    // don't create a new file if contraint are respected
    if (imageConfig.useOriginal(initialWidth, initialHeight, result.currentRotation))
    {
      responseHelper.putInt("width", initialWidth);
      responseHelper.putInt("height", initialHeight);
      fileScan(reactContext, imageConfig.original.getAbsolutePath());
    }
    else
    {
      imageConfig = getResizedImage(reactContext, this.options, imageConfig, initialWidth, initialHeight, requestCode);
      if (imageConfig.resized == null)
      {
        removeUselessFiles(requestCode, imageConfig);
        responseHelper.putString("error", "Can't resize the image");
      }
      else
      {
//        uri = Uri.fromFile(imageConfig.resized);////github 上对应版本的
        uri = RealPathUtil.compatUriFromFile(reactContext, imageConfig.resized);
        BitmapFactory.decodeFile(imageConfig.resized.getAbsolutePath(), options);
        responseHelper.putInt("width", options.outWidth);
        responseHelper.putInt("height", options.outHeight);

        updatedResultResponse(uri, imageConfig.resized.getAbsolutePath());
        fileScan(reactContext, imageConfig.resized.getAbsolutePath());
      }
    }
   ...
}

源代码中,Uri.fromFile(imageConfig.resized)替换为uri = RealPathUtil.compatUriFromFile(reactContext, imageConfig.resized);

public static @Nullable Uri compatUriFromFile(@NonNull final Context context,
                                                  @NonNull final File file) {
        Uri result = null;
        //github 上对应版本的: SDK_INT<21
        if (Build.VERSION.SDK_INT < 24) {
            result = Uri.fromFile(file);
        }
        else {
            final String packageName = context.getApplicationContext().getPackageName();
            final String authority =  new StringBuilder(packageName).append(".provider").toString();
            try {
                result = FileProvider.getUriForFile(context, authority, file);
            }
            catch(IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

源码中,compatUriFromFile方法SDK_INT<21,改成了24,和android 7对应上。测试时没问题,不知道为啥作者用的是21。

查看了react-native-image-crop-picker,开启相机功能时,也是SDK_INT<21

    private void initiateCamera(Activity activity) {

        try {
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File imageFile = createImageFile();

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                mCameraCaptureURI = Uri.fromFile(imageFile);
            } else {
                mCameraCaptureURI = FileProvider.getUriForFile(activity,
                        activity.getApplicationContext().getPackageName() + ".provider",
                        imageFile);
            }

            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraCaptureURI);

            if (cameraIntent.resolveActivity(activity.getPackageManager()) == null) {
                resultCollector.notifyProblem(E_CANNOT_LAUNCH_CAMERA, "Cannot launch camera");
                return;
            }

            activity.startActivityForResult(cameraIntent, CAMERA_PICKER_REQUEST);
        } catch (Exception e) {
            resultCollector.notifyProblem(E_FAILED_TO_OPEN_CAMERA, e);
        }

    }

另一个上传图片的思路就是使用rn-fetch-blob,不是用fetch,返回的uri数据为:file:\\URI。(暂时未验证)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,539评论 25 709
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,751评论 0 17
  • 编辑:豆豆 茫茫人生,或有一人。陷其所爱,忘乎所以。不问初心,不为期望,不望相守,不许相依。只愿烂漫时,与子共相栖...
    迷彩情诗阅读 719评论 0 1
  • 对朋友说,心中抑郁,友答,以你境地,如何抑郁? 也许,在每个人的心里,都有一道别人看不到的阴影。唯自己,与这阴影朝...
    你的杂货店有小小鸟阅读 93评论 0 0
  • 梨花又开放 陈明版本 每次都是临时抱佛脚,上课前短短十来分钟的士上开始用耳机听歌。 我在车上望出窗外繁忙的深南大道...
    Orange_miki阅读 502评论 0 0