Как отправить изображение из приложения React-Native на сервер Django с помощью Expo ImagePicker?
const [image, setImage] = useState(null);
const pickImage = async () => {
// No permissions request is necessary for launching the image library
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(result.uri);
if (!result.cancelled) {
setImage(result);
}
};
Я изучаю React-Native и Django и знаю о FormData, но не понимаю, как их вставить в мой код.
Попробуйте следующий код
const pickImage = async () => {
// No permissions request is necessary for launching the image library
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(result.uri);
if (!result.cancelled) {
postToServer(result)// must be a object not array, if its array find first element if selecting only one image
setImage(result);
}
};
//just function to upload to server
const postToServer = (img)=>{
const formData = new FormData();
formData.append('photo', {
uri: img.uri,
type: 'image/jpeg', // or photo.type
name: 'testPhotoName'
});
const options = {
method: 'POST',
body: formData,
// If you add this, upload won't work
// headers: {
// 'Content-Type': 'multipart/form-data',
// }
};
fetch('your-upload-url', options);
}