[英]How to upload image to server (REACT NATIVE apisauce)
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我怎样才能转换为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.通过反复试验,我已经找到了将图像从 react-native 应用程序上传到 s3 的解决方案,您应该能够添加所需的任何数据作为 url 参数。
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. 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.获取 iOS 图像数据可能有更好的方法,但是当我在今年早些时候写这篇文章时,这 3 步过程是我可以上传 iOS 图像的唯一方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.