React Native文件上传
一、图片上传
//上传图片的库
import * as ImagePicker from 'expo-image-picker'
...
//此处利用ActionSheet控件把上传图片分为从相册选择和拍照两种
const pickImage = async () => {
ActionSheet.showActionSheetWithOptions(
{
options: ['相册','拍照', '关闭',
cancelButtonIndex: 2,
},
async (buttonIndex) => {
try {
if (buttonIndex === 0) {
//相册
uploadImage(ImagePicker.launchImageLibraryAsync)
} else if (buttonIndex === 1) {
//拍照
uploadImage(ImagePicker.launchCameraAsync)
}
} catch (error) {
console.log(error)
}
}
);
};
//真正上传图片的函数
const uploadImage = async (handle: Function) => {
const option = {
allowsEditing: true,
quality: 1,
base64: true,
}
//result为获取的图片信息
let result = await handle(option)
if (!result.cancelled) {
//注:因为我在项目中时使用base64上传图片的,所以此处没有组装数据,如果你是使用multipart/form-data
// 请参考下面文件的上传
try {
//异步操作
...
} catch (error) {
console.log(error)
}
}
}
二、文件的上传
//上传文件的库
import * as DocumentPicker from 'expo-document-picker'
...
const uploadFile = async () => {
//获取文件的基本信息
const result = await DocumentPicker.getDocumentAsync()
const formData = new FormData()
if (result.type === 'success') {
//组装上传的信息(name,uri,type必须要有)
formData.append('file', {
name: result.name,
size: result.size,
//Mimer:根据文件后缀名获取mime类型的库
type: Mimer(result.uri),
uri: Platform.OS === 'android' ? result.uri : result.uri.replace('file:///', ''),
});
//异步操作
...
}
}
注:以上使用的两个库只能用于expo托管的开发模式

浙公网安备 33010602011771号