Home > Enterprise >  React Native - Upload multiple images in one request?
React Native - Upload multiple images in one request?

Time:10-20

So I have this code for uploading images. If I upload a single image it works, but if I upload a list of images then request.FILES will be empty.

  const createFormData = (photos, body = {}) => {
    const data = new FormData();

    if (photos.length > 1) {
      const image_list = [];
      for (var i = 1; i < photos.length; i  ) {
        const photo = photos[i];
        image_list.push({
          name: photo.fileName,
          type: photo.type,
          uri: Platform.OS === "ios" ? photo.uri.replace("file://", "") : photo.uri,
        });
      }
      console.log(image_list)
      data.append("images", image_list);
    }

    Object.keys(body).forEach((key) => {
      data.append(key, body[key]);
    });

    return data;
  };

CodePudding user response:

The Problem

you are trying to append a list of images instead of appending them one by one in data.append("images", image_list);

The Solution:

use append method instead of pushing images into the image_list array:

const data = new FormData();

if (photos.length > 1) {

  for (var i = 1; i < photos.length; i  ) {
    const photo = photos[i];
    data.append('images', {
      name: photo.fileName,
      type: photo.type,
      uri: Platform.OS === "ios" ? photo.uri.replace("file://", "") : photo.uri,
    });
  }
}

Explanation:

according to the MDN, you can append multiple values with the same key:

formData.append('name', true);
formData.append('name', 74);
formData.append('name', 'John');

formData.getAll('name'); // ["true", "74", "John"]

Optional

You can also use forEach function to do the same thing without a for loop:

const data = formData();

if(photos?.length > 1) {
  photos.forEach( (photo) => {
    data.append('images', {
      name: photo.fileName,
      type: photo.type,uri: Platform.OS === "ios" ? photo.uri.replace("file://", "") : photo.uri,
    })
  })
}
  • Related