如何使用expo图像选择器将图像上载到localhost服务器?

时间:2020-10-17 13:34:27

标签: image react-native file-upload frontend multer

我正在尝试使用此组件将图像上传到本地主机,但是每当尝试上传图像时,我都会收到一条错误消息,指出该图像从未上传过。

&

这是服务器代码:

import React, { Component } from 'react';
import { Button, SafeAreaView,
  Image, View } from 'react-native';

import * as ImagePicker from 'expo-image-picker';

class UploadTest extends Component {


  constructor(props) {
    super(props);
    this.state = {
      image: {}
    }

    this.pickImage = this.pickImage.bind(this)
  }



  async pickImage() {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    console.log(result);

    // upload to server
    let uriParts = result.uri.split('.');
    let fileType = uriParts[uriParts.length - 1];

    let formData = new FormData();
    formData.append('image', {
      uri: result.uri,
      name: `photo.${fileType}`,
      type: `image/${fileType}`,
    });

    console.log(JSON.stringify(formData));

    let options = {
      method: 'POST',
      body: formData,
      header: {
        'Accept': 'application/json',
        'Content-Type': 'multipart/form-data'
      },
    };

    if (!result.cancelled) {
      this.setState({
        image: result.uri
      });
    }

    fetch("http://localhost:8080/upload_receipt_img", options)
      .then(result => console.log(result))

  };

  render() {
    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <Button title="Pick an image from camera roll" onPress={this.pickImage} />
          {this.state.image && <Image source={{ uri: this.state.image }} style={{ width: 200, height: 200 }} />}
        </View>
    );
  }
}

我尝试过的测试:

  1. 从标题中删除
  2. 完全删除标头,这消除了边界错误,但使服务器端的文件未定义。
  3. 我删除了接受应用程序/ JSON行无济于事
  4. 我使用了Axios库而不是fetch调用。

0 个答案:

没有答案