I’m building a React Native app that utilizes an image colorization API from RapidAPI. The API has switched from accepting base64 images to requiring direct file uploads, and I’m struggling to get it working properly.
Currently, I’m using react-native-image-picker to select images from the device’s gallery, but I’m unsure how to format the image data correctly for the API request.
Here’s an example of what the API documentation outlines:
import axios from "axios";
const formData = new FormData();
formData.append("photo", "");
formData.append("quality", "30");
const config = {
method: 'POST',
url: 'https://ai-picture-colorizer.p.rapidapi.com/colorize-api-bin-mjbcrab',
headers: {
'content-type': 'multipart/form-data',
'x-rapidapi-host': 'ai-picture-colorizer.p.rapidapi.com',
'x-rapidapi-key': '[API-KEY]'
},
data: formData
};
axios.request(config).then(function (result) {
console.log(result.data);
}).catch(function (err) {
console.error(err);
});
Here’s how my implementation looks:
import React, {Component} from 'react';
import {View, Text, Image, StyleSheet} from 'react-native';
import {Button} from 'react-native-elements';
import {launchImageLibrary} from 'react-native-image-picker';
import axios from 'axios';
export default class PhotoColorizer extends Component {
constructor(props) {
super(props);
this.state = {
showMenu: true,
resultData: null,
isLoading: true,
imageBase64: null,
imageName: null,
};
}
pickFromGallery() {
const pickerOptions = {
includeBase64: true,
};
launchImageLibrary(pickerOptions, result => {
if (result.didCancel) {
console.log('User canceled selection');
} else if (result.error) {
console.log('Picker error occurred');
} else {
this.setState({
imageBase64: result.assets[0].base64,
imageName: result.assets[0].fileName,
});
this.sendToAPI();
}
});
}
sendToAPI() {
const {imageName} = this.state;
const uploadForm = new FormData();
uploadForm.append('photo', imageName);
uploadForm.append('quality', '15');
this.setState({showMenu: false});
axios.request({
method: 'POST',
url: 'https://ai-picture-colorizer.p.rapidapi.com/colorize-api-bin-mjbcrab',
headers: {
'content-type': 'multipart/form-data',
'x-rapidapi-host': 'ai-picture-colorizer.p.rapidapi.com',
'x-rapidapi-key': '[API-KEY]',
},
data: uploadForm,
})
.then(response => {
this.setState({
isLoading: false,
resultData: response.data,
});
})
.catch(error => {
console.error(error);
});
}
}
Unfortunately, I’m encountering a 500 error from the server. Even though the API test endpoint confirms it’s working, it does not provide an example response. How can I accurately format the image data for the upload?