将从 ReactNativeCamera 拍摄的图像发送到具有 multer 的 Nodejs 后端?

send image taken from ReactNativeCamera to Nodejs backend that has multer?

我有一个 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 express 和 multer:

app.post('/scan', uploader.upload.single('file'), ScanController.scan);

Multer 实现得很好,因为它与邮递员和前端 Web 应用程序功能一起使用。

图像显示在 android 设备上,但我在后端总是收到一个未定义的对象,我不知道如何发送它,因为它是基于 64 位的,我该如何发送它或正确接收?

有一个未解决的问题See here on react native about this, but I found a nice solution using rn-fetch-blob

正如您在文档中看到的那样,您可以执行以下操作:

首先,删除 FormData 实例,然后更改 RNFetchBlob.fetch

的提取

代码如下

upload = async () => {
    let ret = await RNFetchBlob.fetch(
      'POST',
      `${Config.BASE_URL}/scan`,
      {
        'Content-Type': 'multipart/form-data',
      },
      [
        {
          name: 'file',
          filename: Date.now() + '.png',
          type: 'image/png',
          data: RNFetchBlob.wrap(data.uri),
        },
      ],
    );
    return ret;
  };

如您所见,有一个数组,您可以在其中添加对象。

Multer 实现和 RNCamera 保持不变。

希望这对某人有用!