簡體   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