我使用 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/