如何确定用户是否选择了视频或图像?

时间:2021-05-19 02:16:11

标签: javascript react-native expo

使用 react native 和 expo,我们希望用户能够发布视频或图片。

代码如下:

import * as ImagePicker from 'expo-image-picker';

const openImagePickerAsync = async() => {
    const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();

    if (permissionResult.granted === false) {
      setImage(null);
      setHasImage(false);
      alert('Permission to access camera roll is required!');
      return;
    }

    const pickerResult = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All, <---------------- allowing photos and video
      allowsEditing: true,
    });

    try {
      if (pickerResult.cancelled === true) {
        setHasImage(false);
        console.log('pickerResult is cancelled');
        return;
      }

      if (pickerResult !== null) {
        setHasImage(true);
        setImage(pickerResult.uri);
        console.log(image);
      } else {
        setImage(null);
        setHasImage(false);
        console.log('pickerResult is null');
        return;
      }
    } catch (error) {
      console.log(error);
    }
  };

我们如何才能知道用户是选择了照片还是视频?是否在元数据中?

1 个答案:

答案 0 :(得分:1)

您应该使用带有视频或图像的 pickerResult.type

您可以参考documentation

<块引用>

Returns 如果用户取消了拣货,则返回 { cancelled: true }. 否则,此方法返回有关所选媒体的信息 物品。当所选项目是图像时,此方法返回 { 取消:假,类型:'图像',uri,宽度,高度,exif,base64 }; 当项目是视频时,此方法返回 { cancelled: false, 类型:'视频'、uri、宽度、高度、持续时间}。