How to upload file using socket.io-stream?

回眸只為那壹抹淺笑 提交于 2019-12-24 05:05:54

问题


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:


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!



来源:https://stackoverflow.com/questions/30025004/how-to-upload-file-using-socket-io-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!