
本文旨在解决 React Native 应用中使用 `react-native-image-crop-picker` 库时,从相册选择图片上传成功,但使用相机拍摄图片上传失败的问题。通过分析 `ImagePicker.openCamera` 和 `ImagePicker.openPicker` 返回数据的差异,并提供针对性的处理方法,确保两种方式都能成功上传图片。
在使用 react-native-image-crop-picker 库开发 React Native 应用时,经常会遇到需要用户上传头像或图片的功能。该库提供了从相册选择图片 (ImagePicker.openPicker) 和使用相机拍摄图片 (ImagePicker.openCamera) 两种方式。然而,有时会发现从相册选择图片上传一切正常,但使用相机拍摄的图片上传却总是失败,并出现类似 "Request failed with status code 504" 的错误。这通常是由于两种方式返回的数据格式存在差异导致的。
问题分析
问题的根源在于 ImagePicker.openCamera 和 ImagePicker.openPicker 返回的图片数据结构不一致,特别是 uri 字段。在上传图片时,需要正确构建 FormData 对象,如果 uri 格式不正确,会导致上传失败。
解决方案
为了解决这个问题,需要针对 ImagePicker.openCamera 和 ImagePicker.openPicker 两种方式分别进行处理,提取并格式化图片数据,使其符合上传要求。
以下是修改后的代码示例:
import ImagePicker from 'react-native-image-crop-picker';
import { Platform } from 'react-native';
import axios, { AxiosResponse } from 'axios';
const API_BASE_URL = 'YOUR_API_BASE_URL'; // 替换为你的 API 地址
const CONFIG_IMAGE_CROP_INVOICE = {
freeStyleCropEnabled: true,
cropperChooseText: 'Crop', // Text for the cropping button
cropperCancelText: 'Cancel', // Text for the cancel button
cropperToolbarTitle: 'Edit Image', // Title for the cropping toolbar
cropperToolbarColor: '#2196F3', // Color for the cropping toolbar
width: 1200,
height: 1500,
cropping: true,
forceJpg: true,
enableRotationGesture: true,
}
const uploadPhotoFromLibrary = image => {
const file = {
uri: image.path,
name: image.path.split("/").pop(),
type: image.mime,
};
return file;
};
const choosePhotoFromLibrary = async () => {
try {
const image = await ImagePicker.openPicker(CONFIG_IMAGE_CROP_INVOICE);
console.log(image);
const file = uploadPhotoFromLibrary(image);
// handle your logic here
await uploadFile(file); // add token to params function to work with your code : uploadFile(receipt, idToken)
} catch (e) {
console.log(e);
}
}
const uploadPhotoFromCamera = image => {
const file = {
name: image?.path.split("/").pop(),
type: image?.mime,
uri:
Platform.OS === 'android' ? image?.path : image?.path.replace('file://', ''),
};
return file;
};
const takePhotoFromCamera = async () => {
try {
const image = await ImagePicker.openCamera(CONFIG_IMAGE_CROP_INVOICE);
console.log(image);
const file = uploadPhotoFromCamera(image);
// handle your logic here
await uploadFile(file); // add token to params function to work with your code : uploadFile(receipt, idToken)
} catch (e) {
console.log(e);
}
}
static uploadFile = async (file: any, idToken: string): Promise => {
return new Promise(async (resolve, reject) => {
console.log("filepath: " + file.uri);
// when taking: filepath: /data/user/0/com.myapp/files/1685872451229.jpg
// when picking: filepath: /data/user/0/com.myapp/files/1685872572898.jpg
const formData = new FormData();
formData.append('file', {
name: file.name,
uri: file.uri,
type: file.type
});
try {
const response = await axios.post(`${API_BASE_URL}`, formData, {
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
Authorization: idToken
}
});
resolve(response);
} catch (error) {
console.error(error);
reject(error);
}
})
} 代码解释:
- uploadPhotoFromLibrary(image) 函数: 用于处理从相册选择的图片,从image对象中提取path,name和mime属性,并构造file对象。
- uploadPhotoFromCamera(image) 函数: 用于处理相机拍摄的图片。 关键在于处理 uri 字段。在 Android 平台上,直接使用 image.path,而在 iOS 平台上,需要使用 image.path.replace('file://', '') 移除 file:// 前缀。 同样从image对象中提取path,name和mime属性,并构造file对象。
- uploadFile(file, idToken) 函数: 接收经过处理后的 file 对象,用于构造 FormData 对象并上传到服务器。file对象中包含name,uri和type属性。
注意事项:
- 确保 react-native-image-crop-picker 库已正确安装并配置。
- 根据实际情况修改 API_BASE_URL 为你的 API 地址。
- uploadFile 函数中的 idToken 需要根据你的认证方式进行传递。
- 在 iOS 平台上,需要在 Info.plist 文件中添加相机和相册的使用权限声明。
- 根据实际需求调整 CONFIG_IMAGE_CROP_INVOICE 的配置,例如 width、height、cropping 等。
总结
通过以上方法,可以有效解决 React Native 应用中使用 react-native-image-crop-picker 库时,相机拍摄图片上传失败的问题。关键在于理解 ImagePicker.openCamera 和 ImagePicker.openPicker 返回数据的差异,并针对性地处理 uri 字段,确保其格式符合上传要求。同时,需要注意不同平台上的差异,以及权限配置等问题。










