Robię aplikację z Expo i chcę pozwolić użytkownikowi zrobić zdjęcie lub wybrać jedną z ich rolek z aparatu i przesłać ją na mój serwer. Jak mam to zrobic?Jak mogę załadować zdjęcie z Expo?
9
A
Odpowiedz
15
Użyj Expo ImagePicker
API wyświetlać w aparacie lub na rolce aparatu i odzyskać informacje o wybranym obrazie:
async function takeAndUploadPhotoAsync() {
// Display the camera to the user and wait for them to take a photo or to cancel
// the action
let result = await ImagePicker.launchCameraAsync({
allowsEditing: true,
aspect: [4, 3],
});
if (result.cancelled) {
return;
}
// ImagePicker saves the taken photo to disk and returns a local URI to it
let localUri = result.uri;
let filename = localUri.split('/').pop();
// Infer the type of the image
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : `image`;
// Upload the image using the fetch and FormData APIs
let formData = new FormData();
// Assume "photo" is the name of the form field the server expects
formData.append('photo', { uri: localUri, name: filename, type });
return await fetch(YOUR_SERVER_URL, {
method: 'POST',
body: formData,
header: {
'content-type': 'multipart/form-data',
},
});
}
Dla bardziej kompleksowy przykład w tym kodzie serwera, zobacz ten repo: https://github.com/exponent/image-upload-example.
2
Oficjalne przykłady użyć node.js, oto jak z PHP:
Expo
async function takePhotoAndUpload() {
let result = await ImagePicker.launchCameraAsync({
allowsEditing: false, // higher res on iOS
aspect: [4, 3],
});
if (result.cancelled) {
return;
}
let localUri = result.uri;
let filename = localUri.split('/').pop();
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : `image`;
let formData = new FormData();
formData.append('photo', { uri: localUri, name: filename, type });
return await fetch('http://example.com/upload.php', {
method: 'POST',
body: formData,
header: {
'content-type': 'multipart/form-data',
},
});
}
upload.php
<?php
move_uploaded_file($_FILES['photo']['tmp_name'], './photos/' . $_FILES['photo']['name']);
?>
Jak przesłać kilka zdjęć na raz? – Vinay
Awesome, thanks! – CoredusK
Człowieku, jesteś zbawicielem. Dziękuję bardzo! –