Jamal
Jamal

Reputation: 848

Pick images in react native and upload it

I want to upload an array of images using react-native-image-crop-picker but I can't fix it.

What I've tried:

export default class Upload extends Component {
  constructor() {
    super();
    this.state = {
      token: '',
      photos: [],
    };
  }

  _TakePhoto() {
    ImagePicker.openPicker({
      multiple: true,
    }).then((images) => {
      images.map((item, index) => {
        ImageResizer.createResizedImage(item.path, 1200, 1200, 'JPEG', 100)
          .then((response) => {
            // console.warn('Resized img is: ', response);
            this.state.photos.push(response);
            console.warn('Resized img state is: ', this.state.photos);
            this._submit_pictures();
          })
          .catch((err) => {});
      });
    });
  }

  _submit_pictures() {
    let formData = new FormData();
    for (let i = 0; i < this.state.photos.length; i++) {
      let file = {
        uri: this.state.photos[0].path,
        // uri: this.state.photos[0].path.replace('file:///', ''),
        // uri: this.state.photos[0].uri,
        type: this.state.photos[0].mime,
        name: this.state.photos[0].name,
      };
      formData.append('pics[]', file);
    }
    //     uri: this.state.photos[0].uri.replace("file:///", "file://"),
    formData.append('postId', postId);
    formData.append('token', token);
    console.log('formData value: ', formData);
    axios({
      url: 'https://rahnama.com/webservice/submitPictures',
      method: 'POST',
      headers: {
        // "Accept": "application/json",
        'Content-Type': 'multipart/form-data',
      },
      // formData
      body: formData,
    })
      .then((response) => {
        console.warn('upload res: ', response);
      })
      .catch((error) => console.warn('upload err: ', error.response.request._response));
  }

  render() {
    return <Text onPress={() => this._TakePhoto()}> Pick </Text>;
  }
}

Upvotes: 0

Views: 525

Answers (1)

Jamal
Jamal

Reputation: 848

Solved it by sending the image data in base64.

1- Pick the image
2- convert it to base64
3- pass the base64 string as the payload

Upvotes: 1

Related Questions