文件未通过socket.io发送

时间:2016-01-15 14:45:17

标签: javascript angularjs node.js sockets socket.io

我正在使用angularjs,nodejs和socketio进行交流。

客户端html:

<div style='height: 0px;width: 0px; overflow:hidden;'>
    <input id="avatarInput" type="file" value="upload" onchange="angular.element(this).scope().upload(this)" />
</div>
<button data-ng-click="avatarButton()">Upload image</button>

客户js:

$scope.avatarButton = function () {
    document.getElementById('avatarInput').click();
}
$scope.upload = function (file) {
    console.log('client: ' + file.type);
    socket.emit('image', {
        file: file
    });  
}

当我选择要打开的client: file文件时,输出结果为.png

服务器nodejs:

.on('image', function (data) {
    console.log('server: ' + data.file.type);
})

以上结果输出:server: undefined

我猜测该文件没有通过socket.io正确发送到服务器。我在这里看不到错误。这里有更多文档:http://socket.io/blog/introducing-socket-io-1-0/#binary

引用文件:

  

Socket.IO现在支持发送缓冲区(来自Node.JS),Blob,   ArrayBuffer甚至File,作为任何数据结构的一部分:

工作代码:

客户端html:

<div style='height: 0px;width: 0px; overflow:hidden;'>
    <input id="avatarInput" type="file" value="upload" onchange="angular.element(this).scope().upload(this.files)" />
</div>
<button data-ng-click="avatarButton()">Upload image</button>

客户js:

    $scope.avatarButton = function () {
        document.getElementById('avatarInput').click();
    }
    $scope.upload = function (files) {
        if (window.File && window.FileReader && window.FileList && window.Blob) {
            socket.emit('uploadAvatar', {
                file: files[0]
            });
        } else {
            alert('The File APIs are not fully supported in this browser.');
        }
    }

服务器nodejs:

    .on('uploadAvatar', co.wrap(function* (data) {
        console.log(data.file); // spits out buffer
        var fs = require('fs');
        fs.writeFile(__dirname + '/public/avatar/myFile.png', data.file, {
            flag: "w"
        }, function (err) {
            if (err)
                return console.log(err);
            console.log("The file was saved!");
        });
    }))

1 个答案:

答案 0 :(得分:0)

应该是这样的(见评论)

$scope.upload = function (element) { //element is an input[file]
    console.log('client: ' + element.files); //a FileList object that can be send
    socket.emit('image', {
        file: element.files //or element.files[0] depending of what you want to achieve
    });  
}