關於react-native-image-picker使用過程中的坑

weixin_33918357發表於2018-08-30

專案中使用的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。(暫時未驗證)

相關文章