skip to Main Content

I am using Axios for API calls. I want to upload an image from mobile to the server. API is accepting data in binary form image. It is working fine from POSTMAN. But I cannot understand how to pass images in Axios in code.

This is the API curl from Postman.

curl --location --request PATCH 'https://{baseURL}/v1/device/image' 
--header 'accept: application/json' 
--header 'Content-Type: image/jpeg' 
--header 'Authorization: Basic MTIwODU4MTM3MTk6Z2tNUWpRVWM=' 
--data '@'

Postman sample api calling.

  try {
  
      // Make the API request
      await request({
        url: 'device/image',
        data: imageData[0].base64, // here what I need to pass exactly.
        method: 'PATCH',
        config: {
          headers: {
            'Content-Type': 'image/jpeg',
            accept: 'application/json',
            maxContentLength: 100000000,
          },
          maxBodyLength: Infinity,
          maxContentLength: Infinity,
          responseType: 'json',
        },
      })
        .then(async (res: ApiResponse<any>) => {
          console.log('res ::: ', res.data);
          // Handle the response as needed
        })
        .catch((e: any) => {
          console.error('Oops :: ', e);
          // Handle the error as needed
          toast.show({
            type: 'error',
            message: e.message || 'Something went wrong',
            position: 'top',
          });
        });
    } catch (error) {
      console.warn('error ::: ', error);
      // Respond with a 500 Internal Server Error if something goes wrong
      return;
    }

this is the file data I get.

{"fileName": "1854487B-07A2-4BFA-9B64-B047202F8877.jpg", "fileSize": 2567402, "height": 2848, "type": "image/jpg", "uri": "file:///Users/theonetech/Library/Developer/CoreSimulator/Devices/FEC6EBCC-8A7E-4D43-B5E7-F5EB9F512EBF/data/Containers/Data/Application/A2FFD8E2-C3EE-45B0-A811-5467E27A761E/tmp/1854487B-07A2-4BFA-9B64-B047202F8877.jpg", "width": 4288}

I found one resource on the internet. https://medium.com/@j.lilian/how-to-use-axios-to-send-binary-data-579c3334ba72

But not able to understand.

2

Answers


  1. Chosen as BEST ANSWER

    I found the solution.

    import { Buffer } from "buffer";
    import { readFile } from "react-native-fs";
    
    // other code.
    
      const updateUserData = async () => {
        if (profileImage) {
          let path = profileImage.uri;
          path = profileImage.uri.replace("file:", "");
          await readFile(path, "base64")
            .then(async (contents: any) => {
              const body = Buffer.from(contents, "base64");
              await request({
                url: "device/image",
                data: body,
                method: "PATCH",
                config: {
                  headers: {
                    "Content-Type": "image/jpeg",
                  },
                },
              })
                .then(async (res: ApiResponse<any>) => {
                  console.log("res ::: ", res.data);
                  // Handle the response as needed
                  login(res.data);
                })
                .catch((e: any) => {
                  console.error("Oops :: ", e);
                  // Handle the error as needed
                  toast.show({
                    type: "error",
                    message: e.message || "Something went wrong",
                    position: "top",
                  });
                });
            })
            .catch((error: any) => console.log({ error }));
        }
    }


  2. enter image description here

    The example assumes you have the binary image data or can obtain it. If you are working with an image picked from the device, you can use a library like react-native-image-picker to get the image data. Adjust the code accordingly based on your specific use case.

    You can use ‘react-native-image-crop-picker’ to pick image and video. Set following property to true

    includeBase64: true

    and image file content will be available as a base64-encoded string in the data property

    ImagePicker.openPicker({
      mediaType: "photo",
      includeBase64: true // this will give 'data' in response 
    })
    .then((response) => {
        console.log(response.data)
    })
    .catch((error) => {
       alert(error)
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search