javascript - 文件未通过 socket.io 发送

标签 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
    });  
}

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

服务器 Node :

.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 now supports emitting Buffer (from Node.JS), Blob, ArrayBuffer and even File, as part of any datastructure:

工作代码:

客户端 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.');
        }
    }

服务器 Node :

    .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!");
        });
    }))

最佳答案

应该是这样的(见评论)

$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
    });  
}

关于javascript - 文件未通过 socket.io 发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34813596/

相关文章:

javascript - 排序多维数组

javascript - react-redux 中的几个同名 Action

node.js - NodeJS 中的 Bootstrap 模态窗口

javascript - 在生产环境中管理快速服务器依赖关系的最佳方法

node.js - bcrypt 哈希与用户登录时的比较

javascript - 获取对象属性?

javascript - 如何在 watch 模式下 sails (开发中)

javascript - 更新 AngularJS 中的父子详细信息

javascript - 如何在 AngularJS 中处理和显示对象数组

css - 在 Angular App 中覆盖 Bootstrap