Upload Multiple Image in React using axios

Viewed 789

I have here a problem with multiple images. My problem is that I want to upload multiples image through an API. The API can't handle it through one request. That's why I wanted to upload images one by one and call the API one by one. How do i do it?

export const saveImages =
  ({ images = [], oldImages, isNew }) =>
  async (dispatch) => {
    try {
      dispatch({
        type: constants.REQUEST,
      });

      let responses;

      if (images?.length) {
        let formData = new FormData();

        const requests = images.map(({ imageFileName, imageFile }) => {
          formData.append(imageFileName, imageFile);
          formData.append("isNewProduct", isNew);
          
          return axios.post(
            `${URL}/saveImages`,
            formData
          );
        });

        responses = await Promise.all(requests);
      }

      dispatch({
        type: constants.SUCCESS,
        payload: [...(oldImages || []), ...response?.data],
      });
    } catch (error) {
      dispatch({
        type: constants.FAILURE,
      });
    }
  };
1 Answers

If you really need to split them up into individual requests then map the images to an array of Promises (axios.post) and await Promise.all(....) them. When all mapped promises resolve then Promise.all resolves.

export const uploadMultipleImages = ({ images }) => async (dispatch) => {
  try {
    dispatch({ type: constants.REQUEST });

    // Map images to array of axios.post Promises
    const requests = images.map(({ imageFileName, imageFile })=> {
      const formData = new FormData();
      formData.append(imageFileName, imageFile);
      return axios.post(`${URL}/upload-image`, formData);
    });

    // await all promises to resolve, responses is an array of all
    // resolved Promise values, i.e. whatever the POST requests
    // return
    const responses = await Promise.all(requests);

    dispatch({
      type: constants.SUCCESS,
      payload: responses,
    });
  } catch (error) {
    dispatch({ type: constants.FAILURE });
  }
};

If I recall correctly on previous questions sometimes the images would have missing properties, so if this is still the case then you may want to use a .filter function before mapping to POST requests.

Related