Ad

Issue Uploading An Image Using Axios

- 1 answer

I'm trying to send an image to my server using axios with react-native.

For doing this, I'm passing the image data (the base 64 encoded image data) directly to an uploadPicture function which uses axios this way:

const uploadPicture = async (data): Promise<AxiosResponse<string>> => {
  const response = publicApi.post(
    `${API_URL}/upload`,
    {
      image: data,
    },
    {
      headers: { 'Content-Type': 'multipart/form-data' },
      transformRequest: [transformToFormData],
    }
  );

  return response;
};

const transformToFormData: AxiosTransformer = data => {
  const formData = new FormData();
  for (const key in data) {
    formData.append(key, data[key]);
  }
  return formData;
};

The issue I face :

I get an internal error, like if my image was not correctly transmitted through my request.

If I'm doing the exact same request using Postman, it works fine, setting the body like this :

enter image description here

Which make me think that the issue doesn't come from my server but from my axios request.

Any idea of what I could be doing wrong ? Am I missing any axios option somewhere ?

Ad

Answer

I managed to find a solution:

  • I used the fetch function from javascript instead of axios
  • I send a file object instead of the data directly
  • I had to disable the react-native network inspect, otherwise the upload won't work

My working solution below, image being the response of react native image picker:

const file = {
    uri: image.uri,
    name: image.fileName,
    type: image.type,
    size: image.fileSize,
    slice: () => new Blob(),
  };

  const body = new FormData();
  body.append('image', file);

  const response = await fetch(`${API_URL}/upload`, {
    method: 'POST',
    body,
  });
Ad
source: stackoverflow.com
Ad