如何使用socket.io-stream上传文件?

时间:2023-02-08 21:16:22

This is my source code.

这是我的源代码。

<server.js>

var app = require('./app.js');
var socketIO = require('socket.io');
var ss = require('socket.io-stream');
var path = require('path');
var fs = require('fs');

var server = app.listen(53322, function() {
    console.log('server is working at port 53322');
});

var io = socketIO.listen(server);

io.on('connection', function (socket) {
    ss(socket).on('file', function(stream, data) {
        console.log(data);
        var filename = path.basename(data.name);
        var filepath = path.join('./uploads', filename);
        var ws = fs.createWriteStream(filepath);
        stream.pipe(ws);
    });

});



<client script>

window.onload = function () {

    var socket = io.connect('http://localhost:53322');

    $('#media-form').submit( function(e) {
        var file = e.target[0].files[0];
        var filename = file.name;
        var filesize = file.size;
        var enc = e.target.encoding;
        var stream = ss.createStream();

        ss(socket).emit('file', stream, {
            data : file,
            size : filesize,
            name : filename,
            enc : enc}
        );

        var blobstream = ss.createBlobReadStream(filename);
        blobstream.pipe(stream);

        return false;
    });

};

I inserted console.log(data); in the server code to check whether the file is uploaded properly. For example, I select 'IMG_4433.jpg' image file in the input element and click submit. After 'file' event done, my console print this message.

我插入了console.log(数据);在服务器代码中检查文件是否正确上传。例如,我在输入元素中选择“IMG_4433.jpg”图像文件,然后单击“提交”。 'file'事件完成后,我的控制台会打印此消息。

{ data: <Buffer ff d8 ff e1 0f fe 45 78 69 66 00 00 4d 4d 00 2a 00 00 00 08 00 0b 01 0f 00 02 00 00 00 06 00 00 00 92 01 10 00 02 00 00 00 0a 00 00 00 98 01 12 00 03 ... >,

size: 393825,

name: 'IMG_4433.JPG',

enc: 'application/x-www-form-urlencoded' }

I found that the 'IMG_4433.jpg' is uploaded into 'uploads' folder. But it's file size is 0 byte. I think that maybe the problem is in the data Buffer... but I don't know how to handle it.

我发现'IMG_4433.jpg'被上传到'uploads'文件夹中。但它的文件大小是0字节。我想也许问题出在数据缓冲区......但我不知道如何处理它。

Help!

1 个解决方案

#1


To make things simpler, I would suggest using something like Dropzone.js It does all the painful work for you and is pretty to use!

为了简单起见,我建议使用像Dropzone.js这样的东西。它为你做了所有痛苦的工作,非常适合使用!

#1


To make things simpler, I would suggest using something like Dropzone.js It does all the painful work for you and is pretty to use!

为了简单起见,我建议使用像Dropzone.js这样的东西。它为你做了所有痛苦的工作,非常适合使用!