我正在用Expo制作一个应用程序,想让用户拍摄一张照片或从他们的相机卷中挑选一张,然后上传到我的服务器上.我该怎么做?

推荐答案

使用Expo ImagePicker API显示相机或相机卷,并获取有关所选图像的信息:

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

有关包含服务器代码的更全面示例,请参阅此repo:https://github.com/exponent/image-upload-example.

React-native相关问答推荐

React Native 中的视图与 Flex 不占用相同的高度空间

导航堆栈不显示

React Native 无法下载模板

使用下拉菜单时react 本机react-native-dropdown-select-list,它会将下面的项目向下移动.如何阻止这种情况发生

使用 Auth Token 标头react 本机图像,如何处理 401?

React Native 应用程序没有在之前的工作代码中执行任何操作就无法运行

导出命名空间应首先由 `@babel/plugin-proposal-export-namespace-from` 转换

如何将 react-native 图像从 expo-image-picker 上传到使用 multer 的 Express.js 后端

在向后滑动时执行操作(react-navigation )

api.get(...).then(...).catch(...).finally 不是函数

NativeBase + Exponent Header

当我导航到react-native 的新页面时,如何强制卸载组件?

在 react-native 和 firebase 3.1 中登录 Facebook

如何将时刻日期转换为字符串并删除时刻对象

expo 已过期卸载并再次运行以升级

在 React-Native 中手动设置 opacity 的 onPress of TouchableOpacity 的音量

按钮的标题属性必须是字符串

如何使用 Jest 测试导入自定义原生模块的 React Native 组件?

在 React Native 中向组件传递参数

zIndex 不适用于react-native元素