简体   繁体   English

socket.io-stream将文件写入磁盘,然后在完成时发出文件路径

[英]socket.io-stream write file to disc then when finished emit file path

I have a problem using socket.io-stream, when I send file from client to server. 将文件从客户端发送到服务器时,使用socket.io-stream时出现问题。 I push file path to mongodb and then save the file to a file-folder. 我将文件路径推送到mongodb,然后将文件保存到文件文件夹。 The problem is that while disc is writing the file, the file path is returned to the client before the writing has complete and then the img element paht is correct but the image does not render on the page. 问题在于,当光盘正在写入文件时,文件路径会在写入完成之前返回到客户端,然后img元素paht是正确的,但是图像不会在页面上呈现。

The code belowe works as expected but im manually waiting 100ms and then returning the path to the client. 下面的代码按预期工作,但我手动等待100毫秒,然后将路径返回给客户端。 Which does not garantee if image is too big this 100ms will do the trick. 如果图像太大,这100ms不会起作用。 Any other solutions ? 还有其他解决方案吗?

Server side: 服务器端:

ss(socket).on('fileUpload', function(stream, data) {
        Chat.findByIdAndUpdate(data.roomId, {
            $push: {
                "messages": {
                    author: data.author,
                    date: Date.now(),
                    isFile: true,
                    extension: data.extension
                }
            }
        },{safe: true, new: true, upsert: true}, (err, message) => {
            if(err){
                console.log(err);
            }

            let msg = message.messages[message.messages.length - 1];
            let filename = path.join(__dirname, 'public/files' , `${msg._id}.${msg.extension}`);
            stream.pipe(fs.createWriteStream(filename));
            setTimeout(() => {
                io.sockets.to(data.roomId).emit('chat-connection', msg);
            },100);
        });
    });

Client Side: 客户端:

function fileUpload(file) {

        let fileExtension = file.name.split('.').pop();
        let stream = ss.createStream();
        // upload a file to the server.
        ss(vm.socket).emit('fileUpload', stream,
            {
                size: file.size,
                extension: fileExtension,
                roomId:vm.chatInstance._id,
                author:$scope.user.fullName,
            });
        ss.createBlobReadStream(file).pipe(stream);
    }

You can check for the finish event on the stream you're writing to. 您可以在要写入的流上检查完成事件。

stream.on('finish', () => {
    io.sockets.to(data.roomId).emit('chat-connection', msg);
});
stream.pipe(fs.createWriteStream(filename));

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

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