react-native: 이미지 업로드

6909 단어 reactnative

필수의




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

}



API 서비스




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);
    }
  },
};

좋은 웹페이지 즐겨찾기