如何使用 Expo 上传照片?

新手上路,请多包涵

我正在使用 Expo 制作一个应用程序,并希望让用户拍照或从他们的相机胶卷中挑选一张并将其上传到我的服务器。我该怎么做呢?

原文由 ide 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
1 个回答

使用 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。

原文由 ide 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题