DEV Community

Nguyễn Hữu Hiếu
Nguyễn Hữu Hiếu

Posted on

react-native: upload image

Required

{
    "dependency": {
        "axios": "0.21", // use this version, the newer version will raise error: multiplepart boundary not found
    }

}

Enter fullscreen mode Exit fullscreen mode

API Service

import {axios} from "axios";
import {Platform} from 'react-native';
export const uploadImageService = {
  // imageUri = "file:///data/user/0/com.company.appname/cache/Camera/58ba8e1b-49cd-4d72-ab01-cf146cc9b69f.jpg"
  uploadImage: async (imageUri: string) => {
    try {
      const url = 'hptt://localhost:3000/upload';
      var photo = {
        name: imageUri.split('/').pop(),
        type: 'image/jpg',
        uri: Platform.OS === 'ios' ? imageUri.replace('file://', '') : imageUri,
      };
      const formData: FormData = new FormData();
      formData.append('file', photo);

      const response = await axios({
        url: url,
        method: 'POST',
        headers: {
          accept: 'application/json',
          'Content-Type': 'multipart/form-data',
        },
        data: formData,
      });

      const json = await response.data;

      console.log('json', json);

      return json.data.link;
    } catch (error) {
      console.log(error);
    }
  },
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)