首页 > 解决方案 > 使用 react-native 返回数据 Image = null

问题描述

我用 react-native-image-crop-picker 创建图像选择器,一切顺利......我从选择器(路径,mime 等)获取数据,但是当我将其上传到服务器时,数据不断返回 null

这是我上传图片的方式:

//this is my state
constructor() {
    super();
    this.state = {
      image: null,
      images: null
    ...
    };
  }
//this is my insert function
doTambah = async => {
    const {
      ...
      image,
    } = this.state;
    
    const req = {
      ...
      foto: image,
    };
    console.log(req);
    api
      .post('/tambah_produk', req)
      .then(res => {
        alert('data berhasil disimpan');
      })
      .catch(err => {
        alert(err);
        console.log(err);
      });
  }

//this is my picker function
pickSingle() {
    ImagePicker.openPicker({
      width: 500,
      height: 500,
      forceJpg: true,
      includeExif: true,
    })
      .then(image => {
        console.log('received image', image);
        this.setState({
          image: {
            uri: image.path,
            width: image.width,
            height: image.height,
            type: image.mime,
            size: image.size
          },
          images: null,
        });
      })
      .catch(e => {
        console.log(e);
        Alert.alert(e.message ? e.message : e);
      });
  }
//this is how I input image inside render
render() {
    ...
    const {
      ...
      image,
      images

    } = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.formWrapper}>
          <View style={styles.formRow}>
            ...
          <View style={{alignItems: 'center', marginBottom: hp('1%')}}>
            <Text style={{alignSelf: 'flex-start'}}>Tambah Foto</Text>
            <ScrollView>
              {this.state.image ? this.renderAsset(this.state.image) : null}
              {this.state.images
                ? this.state.images.map(i => (
                    <View key={i.uri}>{this.renderAsset(i)}</View>
                  ))
                : null}
            </ScrollView>
          </View>
          <TouchableOpacity
            onPress={() => this.pickSingle()}
            style={styles.button}>
            <Text style={styles.text}>Upload Thumbnail</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.btnAddContainer}>
          <TouchableOpacity
            style={styles.btnAdd}
            onPress={() => this.doTambah()}>
            <Text style={styles.textBtnAdd}>Tambah Barang</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

当我尝试记录图像时,返回数据似乎正确

received image {"height": 1080, "mime": "image/jpeg", "modificationDate": "1628874621000", "path": "file:///data/user/0/com.gapoktanapps/cache/react-native-image-crop-picker/IMG-20210813-WA0034.jpg", "size": 78463, "width": 1000}

但是当我将图像上传到服务器时,我不断收到错误:数据:空

响应错误

为什么我的数据:空?怎么了 ?以及如何解决?

标签: react-native

解决方案


尝试使用 FormData 发送帖子数据:

...
const data = new FormData();
data.append('foto', image);

api
   .post('/tambah_produk', data)
   .then(res => {
        alert('data berhasil disimpan');
   })
   .catch(err => {
      alert(err);
      console.log(err);
   });
...

编辑:选择一张图片后,设置名称为image

pickSingle() {
    ImagePicker.openPicker({
      width: 500,
      height: 500,
      forceJpg: true,
      includeExif: true,
    })
      .then(image => {
        console.log('received image', image);
        this.setState({
          image: {
            uri: image.path,
            width: image.width,
            height: image.height,
            type: image.mime,
            size: image.size,
            name: image.path.split('/').pop() // Add this property
          },
          images: null,
        });
      })
      .catch(e => {
        console.log(e);
        Alert.alert(e.message ? e.message : e);
      });
  }

推荐阅读