react native vision camera拍照上传到本地服务器
要在React Native中使用Vision Camera拍照并将照片上传到本地服务器,你需要按以下步骤操作:
- 安装必要的库:
npm install react-native-vision-camera
npm install axios
- 使用Vision Camera拍照并获取图片路径。
- 使用
axios
将图片上传到本地服务器。
以下是一个简化的代码示例:
import React, { useState, useEffect } from 'react';
import { Button, Image, StyleSheet, Text, View } from 'react-native';
import axios from 'axios';
import { VisionCamera, useCameraDevices } from 'react-native-vision-camera';
export default function App() {
const [camera, setCamera] = useState(null);
const [previewUrl, setPreviewUrl] = useState(null);
useEffect(() => {
(async () => {
const { camera } = await VisionCamera.getCameraInfo()[0];
setCamera(camera);
})();
}, []);
const takePhoto = async () => {
if (camera) {
const photo = await camera.takePicture();
setPreviewUrl(photo.uri);
uploadPhoto(photo.uri);
}
};
const uploadPhoto = async (photoUri) => {
const data = new FormData();
data.append('photo', { uri: photoUri, name: 'photo.jpg', type: 'image/jpeg' });
try {
const response = await axios.post('http://your-local-server/upload', data, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
console.log('Photo uploaded:', response.data);
} catch (error) {
console.error('Error uploading photo:', error);
}
};
return (
<View style={styles.container}>
{camera && (
<VisionCamera style={styles.camera} cameraTexture={{}} camera={camera}>
<View style={styles.preview}>
{previewUrl && <Image source={{ uri: previewUrl }} style={styles.image} />}
</View>
</VisionCamera>
)}
<Button title="Take Photo" onPress={takePhoto} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
camera: {
width: '100%',
aspectRatio: 1.0,
},
preview: {
overflow: 'hidden',
aspectRatio: 1.0,
},
image: {
width: '100%',
height: '100%',
resizeMode: 'contain',
},
});
确保替换http://your-local-server/upload
为你的本地服务器的实际上传URL。
注意:本示例假设你的本地服务器配置正确,可以接收上传的图片。在实际应用中,你可能需要处理权限问题、错误处理、优化用户体验等。
评论已关闭