How To Upload Multiple Images To Server using header as multipart/form-data(React-Native)?

Viewed 22

Actually This is not the question but answer, i have been stuck in this problem for almost 2 days, now i want to share my solutions.

First Get Your Image Data in Array

import ImagePicker from 'react-native-image-crop-picker';

chooseImage = () => {
    ImagePicker.openPicker({
      mediaType: "photo",
      width: 300,
      height: 400,
      cropping: true, // cropping won't work even if you set it to true.
      multiple: true, // cropping work's only if multiple is set to false.
      maxFiles: 6, // only work's for IOS
      minFiles: 1,
    }).then((image) => {
      console.log(image); // this is response of the image we are selecting
      console.log(image.length, "Image Length");
      console.log(this.state.imageArray.length, "Array Length");
      // you can have your custom validation
      if(this.state.imageArray.length + image.length >= 6){
        return Alert.alert("Limit Exceeded", "You can only select upto 5 images")
      }
      this.setState((prevState) => ({
        imageArray: [...prevState.imageArray, ...image],
      }));
    });
  };

Now Let's Work On Uploading this Image data to server.

multipleImageUpload = () => {
    const mappedImageArray = this.state.imageArray.map((data: any) => {
      let temp = {
        uri: `${data.path}`,
        type: data.mime,
        name: `${data.path}`
      }
      return temp;
    })
    console.log(mappedImageArray, "MappedIA");
    let formData = new FormData();

    formData.append('account_id', parsedData.id);
    formData.append('description', this.state.description);
    mappedImageArray.forEach((image: any)=> formData.append('post_images[]', image))
    // formData.append('post_images[]', mappedImageArray[0]); // we can use this if we upload only single file
    formData.append('article_id', this.props.route.params.selectedArticleID);

fetch(`${ServerUrl}`, {
      method: 'POST',
      headers: {
           "Content-Type": "multipart/form-data",
           "Authorization" `Bearer ${Token}` // this optional, i used this only because in backend we are making is request little bit secure. 
      },
      body: formData
   }).then(async (response)=> console.log(response))
   .catch(err => console.log(err));

}

So This Is How I managed to solve my Problem, Hope this will help others! Adios!!!

0 Answers
Related