項(xiàng)目中使用的react-native-image-picker的版本是0.26.10,需要拍照或相冊中選一張圖片瑞凑,然后上傳澡罚。
app通過返回的uri加載圖片顯示沒問題,但是上傳圖片有問題敬尺。
使用的是fetch+FormData的方式枚尼。
測試手機(jī)系統(tǒng)有 4.4、6.0筷转、8.0姑原。測試結(jié)果是4.4和6.0系統(tǒng)手機(jī)圖片正常上傳,8.0手機(jī)圖片上傳失敗呜舒。
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的值锭汛,發(fā)現(xiàn)都是file://...
。android 7+系統(tǒng)袭蝗,文件路徑換成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權(quán)限添加,應(yīng)該是大于android7.0系統(tǒng)才需要到腥,因此屏蔽了上面代碼中的if判斷及內(nèi)部代碼朵逝,直接改成
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 上對應(yīng)版本的
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 上對應(yīng)版本的: 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對應(yīng)上。測試時(shí)沒問題瓶佳,不知道為啥作者用的是21芋膘。
查看了react-native-image-crop-picker,開啟相機(jī)功能時(shí),也是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數(shù)據(jù)為:file:\\URI
习寸。(暫時(shí)未驗(yàn)證)