Как узнать размер записанного видео файла в экспо?

Я работаю с выставкой. Я использую экспо-камеру для записи видео. Я получаю URI видео. Но я хочу рассчитать размер видео, прежде чем загружать его (более 5 МБ будут запрещены). Я могу получить только URI видео. Итак, как получить размер видео? Я также искал в Google, но не нашел подходящего ответа.

Компонентный файл

import React, { Component } from "react";
import { View, Text, TouchableOpacity, StyleSheet } from "react-native";
import {
  widthPercentageToDP as wp,
  heightPercentageToDP as hp,
} from "react-native-responsive-screen";
import { Camera } from "expo-camera";

export default class Recordvideo extends React.Component {

// Local State
  state = {
    video: null,
    picture: null,
    recording: false,
    hasPermission: null,
    setHasPermission: "",
  };

// Getting camera permission
 componentDidMount = async () => {
    const { status } = await Camera.requestPermissionsAsync();
    if (status === "granted") {
      this.setState({ hasPermission: true });
    }
  };

 // Getting Video URI After Recording Completed 
_saveVideo = async () => {
    const { video } = this.state;
    console.log(video);
    this.props.navigation.push("Post", {
      VIDEOURL: video.uri,
      VIDEOID: 1,
      mod: true,
    });
  };

// Stop Recording Function
 _StopRecord = async () => {
    this.setState({ recording: false }, () => {
      this.cam.stopRecording();
    });
  };

// Start Recording Function
 _StartRecord = async () => {
    if (this.cam) {
      this.setState({ recording: true }, async () => {
        const video = await this.cam.recordAsync();
        this.setState({ video });
      });
    }
  };

// Toogle function for start/stop recording
  toogleRecord = () => {
    const { recording } = this.state;

    if (recording) {
      this._StopRecord();
    } else {
      this._StartRecord();
    }
  };

// Render function
 render() {
    const { recording, video } = this.state;
    if (this.state.hasPermission === null) {
      return <View />;
    }
    if (this.state.hasPermission === false) {
      return (
        <View
          style={{ flex: 1, alignItems: "center", justifyContent: "center" }}
        >
          <Text>No access to camera</Text>
        </View>
      );
    }

   // return statement
    return (
      <View style={styles.responsiveBox}>
        <Camera
          ref={(cam) => (this.cam = cam)}
          style={{
            justifyContent: "flex-end",
            alignItems: "center",
            flex: 1,
            width: "100%",
          }}
        >

// on Completing Video button, firing _saveVideo Function
          {video && (
            <TouchableOpacity
              onPress={this._saveVideo}
              style={{
                padding: 20,
                width: "100%",
                backgroundColor: "#fff",
              }}
            >
              <Text style={{ textAlign: "center" }}>Complete</Text>
            </TouchableOpacity>
          )}

// on Toggle VideoRecording for start/stop video recording button, firing _toogleRecord Function
          <TouchableOpacity
            onPress={this.toogleRecord}
            style={{
              padding: 20,
              width: "100%",
              backgroundColor: recording ? "#ef4f84" : "#4fef97",
            }}
          >
            <Text style={{ textAlign: "center" }}>
              {recording ? "Stop" : "Record"}
            </Text>
          </TouchableOpacity>
        </Camera>
      </View>
    );
  }
}


  // Styles
const styles = StyleSheet.create({
  responsiveBox: {
    width: wp("100%"),
    height: hp("100%"),
    alignItems: "center",
    justifyContent: "center",
  },
});

person Asif Mushtaq    schedule 21.12.2020    source источник


Ответы (1)


если вы используете expo, вы можете попробовать FileSystem

import * as FileSystem from 'expo-file-system';

getFileSize = async fileUri => {
   let fileInfo = await FileSystem.getInfoAsync(fileUri);
   return fileInfo.size;
 };

иначе установите react-native-fs и используйте метод stat (чтобы получить размер файла )

getFileSize = async fileUri => {
       let fileInfo = await stat(fileUri);
       return fileInfo.size;
     };
person Mehran Khan    schedule 21.12.2020
comment
Спасибо, Мехран, все работает! из-за нового обновления в expo мы должны импортировать его как import * как FileSystem из expo-file-system; - person Asif Mushtaq; 23.12.2020