Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I upload a photo with Expo?

I'm making an app with Expo and want to let the user take a photo or pick one from their camera roll and upload it to my server. How do I do this?

like image 920
ide Avatar asked Mar 01 '17 01:03

ide


People also ask

How do I upload an image to Expo?

To upload a photo with Expo, we can use the expo-image-picker package. We install it by running npm i expo-image-picker . to define the takeAndUploadPhotoAsync that calls ImagePicker. launchCameraAsync to start the camera.

How do I select a picture from the gallery in React Native Expo?

React Native does not provide us with an image picker. For this, we can use an Expo library called expo-image-picker: expo-image-picker provides access to the system's UI for selecting images and videos from the phone's library or taking a photo with the camera.

Can I use Expo for production app?

Your project will always run in one of two modes: development or production. By default, running your project locally with expo start runs it in development mode, whereas a published project (via eas update ), or any standalone apps, will run in production mode.


1 Answers

Use the Expo ImagePicker API to display either the camera or the camera roll and get back information about the selected image:

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',     },   }); } 

For a more comprehensive example including the server code, see this repo: https://github.com/exponent/image-upload-example.

like image 60
ide Avatar answered Sep 18 '22 23:09

ide