【发布时间】:2022-10-17 20:52:44
【问题描述】:
我正在尝试为我的 react 本机应用程序实现一个头像,其中将图片转换为 base64 以使用 GraphQL 存储在 MongoDb 中。我得到的最远的是使用存储 img uri 路径但想要字符串的 imagePicker。
我已尝试对图像进行编码和解码,但一直出错并且应用程序中断
import React, { useContext, useState } from 'react'
import {
SafeAreaView,
Text,
StyleSheet,
View,
Keyboard,
KeyboardAvoidingView,
TouchableWithoutFeedback,
Platform
} from 'react-native'
import { useFonts } from 'expo-font';
import colors from '../../config/colors'
import CustomButton from '../../components/CustomButton';
import { useForm } from 'react-hook-form'
import { useNavigation } from '@react-navigation/core'
import BlueTextInput from '../../components/BlueTextInput';
import AddPicButton from '../../components/AddPicButton';
import * as ImagePicker from 'expo-image-picker';
import AuthContext from '../../context/auth-context'
import { logIn } from '../../util'
const CreateFanProfile = ({ route }) => {
const [image, setImage] = useState(null);
const choosePhotoFromLibrary = async () => {
const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (permissionResult.granted === false) {
alert("Permission to access camera roll is required!");
return;
}
const pickerResult = await ImagePicker.launchImageLibraryAsync();
if (!pickerResult.cancelled) {
setImage(pickerResult.uri);
}
}
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const onNextPressed = async (data) => {
const username = route.params.username;
setEmail(route.params.email);
setPassword(route.params.password);
const role = route.params.role;
const { name, bio } = data;
let requestBody = {
query: `
mutation {
createUser (userInput: {username: "${username}", password: "${password}",
email: "${email}", role: "${role}", name: "${name}", bio: "${bio}",
avatar: "${image}", subscription: false}) {
_id
}
}
`
};
}
if (!loaded) {
return null;
}
return (
<SafeAreaView style={styles.container}>
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
<View style={styles.picContainer}>
<AddPicButton
onPress={choosePhotoFromLibrary}
image={image}
/>
<Text style={styles.bottomText}>ADD A PICTURE</Text>
</View>
</TouchableWithoutFeedback>
</SafeAreaView>
)
}
export default CreateFanProfile
【问题讨论】:
-
这个包可能会帮助
npm install react-native-image-base64 --save -
对于这种情况,是否有更好的解决方案可以将图像直接存储到 mongodb。
-
将base64存储到数据库中不是一个好主意,因为它会减慢速度,将它们作为base64发送。然后在服务器端转换回文件。然后将它们存储到磁盘中
-
有没有比base 64更好的方法来做到这一点 - @ndotie
标签: reactjs mongodb react-native graphql base64