React Native 如何判断用户选择的是视频还是图片?

mkshixfv  于 2023-04-07  发布在  React
关注(0)|答案(2)|浏览(169)

使用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);
    }
  };

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

htrmnn0y

htrmnn0y1#

您应该使用pickerResult.type,其中包含视频或图像
您可以参考文档
返回如果用户取消挑库,则返回{ cancelled:true }。否则,此方法返回有关所选媒体项的信息。当所选项是图像时,此方法返回{ cancelled:false,type:};};};};当项目是视频时,此方法返回{ cancelled:false,type:'video',uri,width,height,duration }.

tzxcd3kk

tzxcd3kk2#

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

const openImagePickerAsync = async() => {
  let result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ImagePicker.MediaTypeOptions.All,
    allowsEditing: true,
    quality: 1,
  });
  
  let index = 0 // simple use case

  if (result.assets[index].type == "image") {
    console.log('image')
  } else if (result.assets[index].type == "video") {
    console.log('video')
  } else {
    console.log('none')
  }
}

相关问题