Successfully post new ad but images upload not working
import client from "./client";
import {API_KEY} from "./constant";
const addListing = (postData,locationId,img) =>
client.post(`api.php?key=${API_KEY}&type=insert&object=item&action=add&catId=${postData.category}&contactName=&contactPhone=${postData.mobile}&sPhone=${postData.mobile}&showPhone=1&contactEmail=${postData.mobile}@kippee.com&price=${postData.price}&countryId=in®ionId=&cityId=${locationId}&title[en_US]=${postData.title}&description[en_US]=${postData.description}&photos=[${imgUrl}]`);
how can i convert to formdata
Through allot of trial and error I've landed on this solution for uploading images to s3 from a react-native app, you should be able to add any data you need as url parameters.
let xhr = new XMLHttpRequest();
xhr.open('PUT', media.putURL); // where you want to put the image
xhr.upload.addEventListener('progress', (event) => {
if (event.lengthComputable) {
let percentComplete = (event.loaded / event.total) * 100;
}
});
xhr.upload.addEventListener('error', () => {
// error
});
xhr.onload = () => {
console.log('onload', xhr.status);
// finished
};
xhr.onreadystatechange = () => {
console.log('xhr.status ', xhr.status);
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// success
} else {
// upload error
}
}
}
xhr.setRequestHeader('Content-Type', 'image/jpg');
if(Platform.OS === 'android'){
xhr.send({uri: media.uri, type: 'image/jpg', name: media.name});
} else {
RNFetchBlob.fs.readFile(media.uri, 'base64', 4095).then((data) => {
let url = "data:image/jpg;base64,"+data
fetch(url).then(res => res.blob()).then((blob) => {
xhr.send(blob);
})
}).catch((error) => {
console.log('Error reading file: ', error);
})
}
If iOS the rn-fetch-blob package needs to be used to fetch the base64 encoded image data, then using the fetch api the blob data is fetched from the base64 encoded string which can then be passed to the xhr send function.
There's likely a better way of fetching iOS image data but when i wrote this earlier in the year this 3 step process was the only way i could get iOS images uploading.