使用react-native-image-crop-picker上传React-Native axios图像

时间:2019-11-17 15:42:32

标签: node.js react-native

大家好,我使用带有React-Native-image-crop-Picker的Axios将图像上传到Node.js,但是我无法上传出现错误[Error: Network Error]的文件

我的Node.js代码一切正常,可以正常使用邮递员,但是我的react-native代码出问题了。请检查一下代码。

本机代码

async upload_File() {
    if (this.validate_Fields()) {
      const { image, images, video, files, description, user_id } = this.state;

      if (this.state.type === 'image/jpeg') {
        console.log('upload_ files ::: ', files);
        console.log('upload_ files ::: ', files);
        const formData = new FormData();
        formData.append('description', description);
        formData.append('user_id', user_id);

        for (let i = 0; i < files.length; i++) {
          formData.append("files[]", files[i]);
        }

        axios.post(API_URL + '/fileuploadapi/uploadPost', formData, {

          headers: {

            'Content-Type': 'multipart/form-data',
          },
        })
          .then((response) => {
            console.log(JSON.parse(JSON.stringify(response.status)));
            this.cleanupImages();
            Alert.alert('Upload Post Successfully ' + '');
          })
          .catch((error) => {
            console.log(error);
            Alert.alert('image Upload Post Failed  , Try again !');
          });

      }
      if (this.state.type === 'video/mp4') {
        console.log('upload_ files ::: ', files);
        axios.post(API_URL + '/fileuploadapi/uploadPost', {
          description: description,
          user_id: user_id,
          files: image,
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        })
          .then((response) => {
            console.log(JSON.parse(JSON.stringify(response.status)));
            this.cleanupImages();
            Alert.alert('Upload Post Successfully ' + '');
          })
          .catch((error) => {
            console.log(error);
            Alert.alert('Video Upload Post Failed  , Try again !');
          });

      }


    }
  }

后端代码:

router.post('/uploadPost', upload.array("files[]", 12), function (req, res, next) {

  if (!req) {
    return res.status(500).json({ error: err });
  } else {
    console.log('Upload files:=> ', req.files)
    console.log('body', req.body)
    var user_id = req.body.user_id;
    var description = req.body.description;


    var sql = "INSERT INTO posts ( user_id, description ) VALUES ( ' " + user_id + " ', ' " + description + "' )";

    connection.query(sql, (err, results, fields) => {

      if (!err) {

        for (var i = 0; i < req.files.length; i++) {
          var post_id = results.insertId;
          var file_name = req.files[i].originalname;
          var type = req.files[i].mime;
          var size = req.files[i].size;
          var saved_name = req.files[i].filename;
          var file_path = req.files[i].path;

          var sql_files = "INSERT INTO files ( post_id, user_id, file_name, mimetype, size, saved_name, file_path ) VALUES ( '" + post_id + "' , '" + user_id + "', '" + file_name + "', '" + type + "', '" + size + "', '" + saved_name + "', '" + file_path + "' )";
          connection.query(sql_files, (err, rows, fields) => {
            if (!err) {
              console.log({ 'originalname': file_name, 'uploadname': saved_name });

            } else {
              console.log(err);

            }
          }); 
        } 

        return res.json({ "status": 200, "error": null, 'success': 'post Uploaded Successfully ', "response": "success" });

      } else {
        console.log(err);
        return res.status(500).send({ 'error': 'post not uploaded' });
      }
    });
  }

});

如果我的代码租约中有任何错误,请通知我。

1 个答案:

答案 0 :(得分:0)

我得到了我的问题的答案

反应本机代码:


 upload_File() {
    if (this.validate_Fields()) {
      const { image, images, files, description, user_id } = this.state;
      // this.setState({ error: '', loading: true });

      if (this.state.type === 'image/jpeg') {
        console.log('upload_ files :::=> ', files);
        const formData = new FormData();
        formData.append('user_id', user_id);
        formData.append('description', description);
        // formData.append('files[]', files);
        for (let i = 0; i < files.length; i++) {
          formData.append('files[]', {
            name: files[i].path.split('/').pop(),
            type: files[i].mime,
            uri: Platform.OS === 'android' ? files[i].path : files[i].path.replace('file://', ''),
          });
        }
        axios.post(API_URL + '/fileuploadapi/uploadPost', formData, {
          headers: { "Content-type": "multipart/form-data" }
        }).then((response) => {
          console.log(JSON.parse(JSON.stringify(response.status)));
          this.cleanupImages();
          Alert.alert('Upload Post Successfully ' + '');
        }).catch((error) => {
          console.log(error);
          Alert.alert('image Upload Post Failed  , Try again !');
        });
      }

      if (this.state.type === 'video/mp4') {
        console.log('upload_ files :::=> ', this.state.files);
        const formData = new FormData();
        formData.append('user_id', user_id);
        formData.append('description', description);
        formData.append('files[]', {
          name: this.state.fileName,
          type: this.state.type,
          uri: Platform.OS === 'android' ? files.path : files.path.replace('file://', ''),
        });
        axios.post(API_URL + '/fileuploadapi/uploadPost', formData, {
          headers: { "Content-type": "multipart/form-data" }
        }).then((response) => {
          console.log(JSON.parse(JSON.stringify(response.status)));
          this.cleanupImages();
          Alert.alert('video Upload Post Successfully ' + '');
        }).catch((error) => {
          console.log(error);
          Alert.alert('video Upload Post Failed  , Try again !');
        });

      }

      if (this.state.type === "image/cam") {
        console.log('upload_ files :::=> ', this.state.files);
        const formData = new FormData();
        formData.append('user_id', user_id);
        formData.append('description', description);
        formData.append('files[]', {
          name: this.state.fileName,
          type: this.state.type,
          uri: Platform.OS === 'android' ? files.path : files.path.replace('file://', ''),
        });
        axios.post(API_URL + '/fileuploadapi/uploadPost', formData, {
          headers: { "Content-type": "multipart/form-data" }
        }).then((response) => {
          console.log(JSON.parse(JSON.stringify(response.status)));
          this.cleanupImages();
          Alert.alert('camera Upload Post Successfully ' + '');
        }).catch((error) => {
          console.log(error);
          Alert.alert('camera Upload Post Failed  , Try again !');
        });

      }


    }
  }


renderVideo(image) {
    console.log('rendering video');
    return (<View style={{ height: 300, width: '100%' }}>
      <Video
        source={{ uri: this.state.files.path }}
        style={{ width: '100%', height: 300 }}
        resizeMode="cover"
        paused={this.state.paused}
        controls={true}

        volume={this.state.volume}
        muted={this.state.muted}
        paused={this.state.paused}

        onLoad={this.onLoad}
        onBuffer={this.onBuffer}
        onProgress={this.onProgress}
      />
    </View>);
  }
  renderImage(image) {
    return <Image style={{ width: '100%', height: 500, resizeMode: 'cover', marginBottom: 6, borderRadius: 2, borderColor: 'green', borderWidth: 1, }} source={image} />
  }
  renderAsset(image) {
    if (image.mime && image.mime.toLowerCase().indexOf('video/') !== -1) {
      return this.renderVideo(image);
    }
    return this.renderImage(image);
  }

  pickMultipleImages() {
    ImagePicker.openPicker({
      multiple: true,
      mediaType: "photo",
      // waitAnimationEnd: false,
      // includeExif: true,
      // forceJpg: true,
    }).then(images => {
      // console.log('received images', images);
      console.log('received images mime:=>', images.mime);
      this.setState({
        type: "image/jpeg",
        image: null,
        files: images,
        images: images.map(i => {
          // console.log('received image', i);
          console.log('received images mime::::', i.mime);
          return { uri: i.path, width: i.width, height: i.height, mime: i.mime };
        })
      });
    }).catch(error => {
      console.log(error);
      Alert.alert(error.message ? error.message : error);
    });
  }

  pickSingleVideo() {
    ImagePicker.openPicker({
      mediaType: "video",
      // compressVideoPreset: 'MediumQuality',
      // includeExif: true,
    }).then(image => {
      console.log('received image', image);
      console.log('received image mime', image.mime);
      console.log('received file-memetype:', image.path.split('.').reverse()[0])
      console.log('received fileName:', image.path.split('/').pop())
      this.setState({
        images: null,
        files: image,
        type: image.mime,
        fileName: image.path.split('/').pop(),
        image: { uri: image.path, width: image.width, height: image.height, mime: image.mime },
      });
    }).catch(error => {
      console.log(error);
      Alert.alert(error.message ? error.message : error);
    });
  }

  pickSingleWithCamera() {
    ImagePicker.openCamera({
      // cropping: cropping,
      // cropping: true,
      // width: 600,
      // height: 500,
      // includeExif: true,
      // mediaType: 'video',
    }).then(image => {
      console.log('received image', image);
      console.log('received image mime: ', image.mime);
      this.setState({
        images: null,
        files: image,
        type: "image/cam",
        // type: "video/mp4",
        fileName: image.path.split('/').pop(),
        image: { uri: image.path, width: image.width, height: image.height, mime: image.mime },
      });
    }).catch(error => {
      console.log(error);
      Alert.alert(error.message ? error.message : error);
    });
  }

  // clear files data 
  cleanupImages() {
    this.setState({
      // description: '',
      image: null,
      images: null,
      // video: '',
      files: '',
    })
    ImagePicker.clean().then(() => {
      console.log('removed tmp images from tmp directory');
    }).catch(error => {
      alert(error);
    });
  }

<View style={styles.mediaComponent}>

                <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>

```````````````````