Después de indagar en varios repositorios y sitios webs finalmente hemos descubierto la solución que te enseñamos aquí.
Solución:
Usa la Expo ImagePicker
API para mostrar la cámara o el carrete de la cámara y recuperar información sobre la imagen seleccionada:
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,
headers:
'content-type': 'multipart/form-data',
,
);
Para obtener un ejemplo más completo que incluye el código del servidor, consulte este repositorio: https://github.com/exponent/image-upload-example.
Los ejemplos oficiales usan Node.js, así es como con 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
import React, Component from 'react';
import
ActivityIndicator,
Button,
Clipboard,
Image,
Share,
StatusBar,
StyleSheet,
Text,
TouchableOpacity,
View,
from 'react-native';
import Constants from 'expo';
import * as Permissions from 'expo-permissions';
import * as ImagePicker from 'expo-image-picker';
export default class App extends Component
state =
image: null,
uploading: false,
;
render()
let
image
= this.state;
return (
Example: Upload ImagePicker result
this._maybeRenderImage()
this._maybeRenderUploadingOverlay()
);
_maybeRenderUploadingOverlay = () =>
if (this.state.uploading)
return (
);
;
_maybeRenderImage = () =>
let
image
= this.state;
if (!image)
return;
return (
image
);
;
_share = () =>
Share.share(
message: this.state.image,
title: 'Check out this photo',
url: this.state.image,
);
;
_copyToClipboard = () =>
Clipboard.setString(this.state.image);
alert('Copied image URL to clipboard');
;
_takePhoto = async () =>
const
status: cameraPerm
= await Permissions.askAsync(Permissions.CAMERA);
const
status: cameraRollPerm
= await Permissions.askAsync(Permissions.CAMERA_ROLL);
// only if user allows permission to camera AND camera roll
if (cameraPerm === 'granted' && cameraRollPerm === 'granted')
let pickerResult = await ImagePicker.launchCameraAsync(
allowsEditing: true,
aspect: [4, 3],
);
if (!pickerResult.cancelled)
this.setState( image: pickerResult.uri );
this.uploadImageAsync(pickerResult.uri);
;
_pickImage = async () =>
const
status: cameraRollPerm
= await Permissions.askAsync(Permissions.CAMERA_ROLL);
// only if user allows permission to camera roll
if (cameraRollPerm === 'granted')
let pickerResult = await ImagePicker.launchImageLibraryAsync(
allowsEditing: true,
base64: true,
aspect: [4, 3],
);
if (!pickerResult.cancelled)
this.setState( image: pickerResult.uri);
this.uploadImageAsync(pickerResult.uri);
;
uploadImageAsync(pictureuri)
let apiUrl = 'http://123.123.123.123/ABC';
var data = new FormData();
data.append('file',
uri: pictureuri,
name: 'file',
type: 'image/jpg'
)
fetch(apiUrl,
headers:
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
,
method: 'POST',
body: data
).then(
response =>
console.log('succ ')
console.log(response)
).catch(err =>
console.log('err ')
console.log(err)
)
const styles = StyleSheet.create(
container:
alignItems: 'center',
flex: 1,
justifyContent: 'center',
,
exampleText:
fontSize: 20,
marginBottom: 20,
marginHorizontal: 15,
textAlign: 'center',
,
maybeRenderUploading:
alignItems: 'center',
backgroundColor: 'rgba(0,0,0,0.4)',
justifyContent: 'center',
,
maybeRenderContainer:
borderRadius: 3,
elevation: 2,
marginTop: 30,
shadowColor: 'rgba(0,0,0,1)',
shadowOpacity: 0.2,
shadowOffset:
height: 4,
width: 4,
,
shadowRadius: 5,
width: 250,
,
maybeRenderImageContainer:
borderTopLeftRadius: 3,
borderTopRightRadius: 3,
overflow: 'hidden',
,
maybeRenderImage:
height: 250,
width: 250,
,
maybeRenderImageText:
paddingHorizontal: 10,
paddingVertical: 10,
);
Reseñas y puntuaciones de la guía
Agradecemos que quieras patrocinar nuestra labor ejecutando un comentario y dejando una valoración te damos la bienvenida.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)