我有这样的代码
var reader = new FileReader();
reader.onload = function(){
socket.emit('test', reader.result);
};
reader.readAsArrayBuffer(uploadHandler.files[0]);
它从
获取文件<input type="file" />
和&#34;转换&#34;它到ArrayBuffer,然后通过WebSockets(Socket.io使用)发送到Node.js服务器,我试图像这样保存它
socket.on('test', function(request) {
require('fs').writeFileSync('../files/test.png', Buffer.from(request));
});
但我得到 TypeError:这不是一个打字数组。
server > 04-29 12:21:22: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 │
00 00 01 1e 00 00 00 66 08 06 00 00 00 1d cf fe ce 00 00 0c 13 69 43 43 50 49 43 │
43 20 50 72 6f 66 69 ... > │
server > TypeError: this is not a typed array. │
server > at Function.from (native) │
server > at Socket.<anonymous> (/home/htdocs/socket/server/server.js:201:65) │
server > at emitOne (events.js:77:13) │
server > at Socket.emit (events.js:169:7) │
server > at /home/htdocs/socket/server/node_modules/socket.io/lib/socket.js:5 │
03:12 │
server > at nextTickCallbackWith0Args (node.js:419:9) │
server > at process._tickDomainCallback (node.js:389:13)
Node.js版本是LTS 6.10.2,所以据我所知,我不需要从ArrayBuffer制作Uint8Array,只能使用Buffer.from方法,但错误仍然存在。
答案 0 :(得分:2)
发现,无论您将文件发送到Socket.io的方式如何,在服务器端ArrayBuffer或File,它都已作为Buffer,因此无需致电Buffer.from你可以写
socket.on('test', function(buffer) {
require('fs').writeFileSync('../files/test.png', buffer);
});
它有效:)