繁体   English   中英

使用socket.io和react-native-fs从react-native上传文件

[英]Upload a file from react-native with socket.io and react-native-fs

我想从我的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
}

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

谢谢你,巴斯蒂安

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

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

使用这个npm包

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM