4

Hello everyone i am using Axios with React-Native-image-crop-Picker for image upload to Node.js , but i am unable to upload the files getting error [Error: Network Error]

Everything okay with my Node.js code it is working with postman fine, but there is something wrong with my react-native code.Please once check the code .

React-Native code

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 !');
          });

      }


    }
  }

Backend code :

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' });
      }
    });
  }

});

If anything wrong in my code lease let me know .

1 Answer 1

3

I got the answer for my question

React native code :


 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>

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for sharing, it was helpful and saved me hours of work
callback file response from react-native-image-crop-picker is just not normal file you can use. Yes, This is great answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.