How to upload a photo with Expo?

Sometimes, we want to upload a photo with Expo.

In this article, we’ll look at how to upload a photo with Expo.

How to upload a photo with 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.

Then we use it by writing:

import * as React from 'react';
import { View, Text } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';
import * as ImagePicker from 'expo-image-picker';

const takeAndUploadPhotoAsync = async () => {
  let result = await ImagePicker.launchCameraAsync({
    allowsEditing: true,
    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('https://https://jsonplaceholder.typicode.com/', {
    method: 'POST',
    body: formData,
    headers: {
      'content-type': 'multipart/form-data',
    },
  });
};
export default function App() {
  React.useEffect(() => {
    takeAndUploadPhotoAsync();
  }, []);

  return <View></View>;
}

to define the takeAndUploadPhotoAsync that calls ImagePicker.launchCameraAsync to start the camera.

Then we get the result after the picture is taken with result.uri.

Next, we get the filename with localUri.split('/').pop().

And then we get the MIME type with match ? `image/${match[1]}` : `image`.

Next, we create a new FormData instance and append the photo to that.

And then we call fetch to submit the FormData instance.

Conclusion

To upload a photo with Expo, we can use the expo-image-picker package.

We install it by running npm i expo-image-picker.