我在React Native上有一个前端,并且实现了以下内容:
import React,{Component} from 'react';
import Config from 'react-native-config';
import {
Button,Alert,Image,Text,View,StyleSheet,TouchableOpacity,Platform,CameraRoll,} from 'react-native';
import {Container,Content,Icon} from 'native-base';
import {RNCamera} from 'react-native-camera';
import {SubHeader} from '../../components/headers';
const styles = StyleSheet.create({
container: {
flex: 1,flexDirection: 'column',backgroundColor: 'black',},preview: {
flex: 1,justifyContent: 'flex-end',alignItems: 'center',capture: {
flex: 0,backgroundColor: '#fff',borderRadius: 5,padding: 15,paddingHorizontal: 20,alignSelf: 'center',margin: 20,});
export default class MainScreen extends Component {
constructor(props) {
super(props);
this.state = {
imageUri: null,};
}
test = async () => {
if (this.camera) {
const data = await this.camera.takePictureAsync({
quality: 0.5,base64: true,});
const photo = {
name: data.fileName,type: data.type,uri:
Platform.OS === 'android'
? data.uri
: data.uri.replace('file://',''),};
this.setState({imageUri: data.uri}); //preview
const fdata = new FormData();
fdata.append('file',photo);
try {
let response = await fetch(`${Config.BASE_URL}/scan`,{
method: 'POST',body: JSON.stringify(fdata),//body: fdata //this launches a connection error
});
const res = await response.json();
return res;
} catch (error) {
console.error(error);
}
} else {
Alert.alert('debug','There is no camera');
}
};
render() {
const {navigate} = this.props.navigation;
return (
<View style={styles.container}>
<RNCamera
ref={ref => {
this.camera = ref;
}}
style={styles.preview}
type={RNCamera.Constants.Type.back}
flashMode={RNCamera.Constants.flashMode.off}
captureAudio={false}
androidCameraPermissionOptions={{
title: 'Permission to use camera',message: 'We need your permission to use your camera',buttonPositive: 'Ok',buttonNegative: 'Cancel',}}
onGoogleVisionBarcodesDetected={({barcodes}) => {
console.log(barcodes);
}}
/>
<View>
<TouchableOpacity
onPress={this.test.bind(this)}
style={styles.capture}>
<Icon type="FontAwesome" ios="camera" android="camera" />
</TouchableOpacity>
</View>
</View>
//preview
<Image
style={{width: 66,height: 58}}
source={{
uri: this.state.imageUri,}}
/>
</View>
);
}
}
在具有nodeJs表达和multer的后端:
app.post('/scan',uploader.upload.single('file'),ScanController.scan);
Multer的实现很好,因为它与邮递员和前端Web应用程序功能一起工作。
该图像显示在android设备上,但是后端总是出现一个未定义的对象,我不知道如何发送该图像,因为它基于base 64,如何正确发送或接收该图像?