How to upload file using socket.io-stream?

2019-07-21 14:51发布

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.

{ 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.

Help!

1条回答
2楼-- · 2019-07-21 15:21

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!

查看更多
登录 后发表回答