1

我想从我的 react-native 应用程序在我的 socket.io 服务器上上传一个视频,从一个 html-js 客户端,上传工作完美。

当我尝试使用 react-native 执行此操作时,该文件已发送,但在服务器上以文本形式找到,之后我无法读取它。

拍摄后保存的视频文件在手机图库中清晰可辨。

import Camera from "react-native-camera";
import SocketIOClient from 'socket.io-client';
import RNFS from 'react-native-fs';

export default class CaptureVideoScreen extends React.Component {

    constructor(props) {
        super(props);

        this.socketInit();

        this.camera = null;
        this.file = null;

        this.state = {
            camera: {
                aspect: Camera.constants.Aspect.fill,
                captureTarget: Camera.constants.CaptureTarget.cameraRoll,
                type: Camera.constants.Type.back,
                captureQuality: "720p",
                flashMode: Camera.constants.FlashMode.auto,
            },
            isRecording: false
        };
    }

    socketInit = () => {
        this.socket = SocketIOClient('https://mywebsite.fr:3001');
        this.socket.on('Upload.RequestData', this.emitData);
        this.socket.on('Upload.Done', this.uploadDone);
    };

    startRecording = () => {
        if (this.camera && !this.state.isRecording) {
            this.camera.capture({mode: Camera.constants.CaptureMode.video})
                .then((data) => {

                    RNFS.readFile(data.path, 'base64').then(contents => {

                        this.file = contents;
                        this.socket.emit('Upload.Start', {'size': contents.length});
                    });
                })
                .catch(err => console.error(err));
            setTimeout(this.stopRecording, 12000);
            this.setState({
                isRecording: true
            });
        }
    };

    stopRecording = () => {
        if (this.camera && this.state.isRecording) {
            this.camera.stopCapture();
            this.setState({
                isRecording: false
            });
        }
    };

    emitData = (data) => {
        var buffer = this.file.slice(data.cursor, data.cursor + data.blockSize);
        console.log(buffer.length);
        this.socket.emit('Upload.Data', {token: data.token, data: buffer});
        console.log(Math.round(data.cursor / this.file.length * 100) + '%');
    };

    uploadDone = (data) => {
        console.log('Upload Done !');
    };

    //... render + camera methods
}

是编码问题吗?如何使用缓冲区读取文件?

谢谢你,巴斯蒂安

4

1 回答 1

0

encode(buffer) - 将 ArrayBuffer 编码为 base64 字符串

decode(str) - 将 base64 字符串解码为 ArrayBuffer

使用这个 npm 包

https://www.npmjs.com/package/base64-arraybuffer

于 2017-09-27T09:39:13.177 回答