项目中使用的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
。(暂时未验证)