I’m having trouble connecting react-native-image-picker with a RapidAPI photo enhancement service. The API changed from base64 format to file uploads but I can’t get it working properly.
When I try to send the image I keep getting a 500 error. The API documentation shows this setup:
import axios from "axios";
const formData = new FormData();
formData.append("photo", "");
formData.append("quality", "30");
const config = {
method: 'POST',
url: 'https://photo-enhancer.p.rapidapi.com/enhance-photo-endpoint',
headers: {
'content-type': 'multipart/form-data',
'x-rapidapi-host': 'photo-enhancer.p.rapidapi.com',
'x-rapidapi-key': 'YOUR_API_KEY'
},
data: formData
};
axios.request(config).then(function (result) {
console.log(result.data);
}).catch(function (err) {
console.error(err);
});
My React Native code looks like this:
import React, {Component} from 'react';
import {View, Text, StyleSheet} from 'react-native';
import {Button} from 'react-native-elements';
import {launchImageLibrary} from 'react-native-image-picker';
import axios from 'axios';
export default class PhotoApp extends Component {
constructor(props) {
super(props);
this.state = {
showMenu: true,
result: null,
isLoading: true,
imageData: null,
imageName: null,
};
}
pickImageFromGallery() {
const settings = {
includeBase64: true,
};
launchImageLibrary(settings, result => {
if (result.didCancel) {
console.log('User cancelled');
} else if (result.error) {
console.log('Picker error');
} else {
this.setState(
{
imageData: result.assets[0].base64,
imageName: result.assets[0].fileName,
},
() => console.log('image name ', this.state.imageName),
);
this.sendToAPI();
}
});
}
sendToAPI() {
const {imageName} = this.state;
const formData = new FormData();
formData.append('photo', imageName);
formData.append('quality', '15');
this.setState({showMenu: false});
console.log('Sending request');
axios
.request({
method: 'POST',
url: 'https://photo-enhancer.p.rapidapi.com/enhance-photo-endpoint',
headers: {
'content-type': 'multipart/form-data',
'x-rapidapi-host': 'photo-enhancer.p.rapidapi.com',
'x-rapidapi-key': 'YOUR_API_KEY',
},
data: formData,
})
.then(response => {
this.setState({
isLoading: false,
result: response.data,
});
})
.catch(error => {
console.error(error);
});
}
}
I think I’m not formatting the image data correctly for the FormData. How should I properly send the picked image to the API?