如何从websocket连接保存来自客户端的传入文本文件

我试图在node.js中实现一个websocket服务器,而不使用任何框架。 从客户端发送消息到服务器工作正常。 但是现在我试图从客户端发送一个文本文件到服务器。 我可以通过在terminal中使用console.log来查看服务器端的内容。 但:

  1. 我如何获得文件信息? (姓名,创build/编辑date等?)

  2. 我怎样才能保存文件?

客户代码:

(function () { 'use strict'; var output, ws; //Display logging information in the document function log(s) { var p = document.createElement("p"); p.style.wordWrap = "break-word"; p.textContent = s; output.appendChild(p); //Also log information on the javascript console window.console.log(s); } //Send a message on the Websocket function sendMessage(msg) { console.log(ws.binaryType); ws.send(msg); console.log("Message sent"); } //Initialize WebSocket connection and event handlers function setup() { output = document.getElementById("output"); ws = new window.WebSocket("ws://localhost:9999/"); //Listen for the connection open event then call the sendMessage function ws.onopen = function () { console.log("Connected"); document.getElementById('fl').onchange = function() { sendMessage(document.querySelector('input[type="file"]').files[0]); }; sendMessage("Hello Galileo!"); } //Listen for the close connection event ws.onclose = function (e) { if(this.readyState == 2){ console.log('Connection is closing (Closing Handshake).') } else if(this.readyState == 3){ console.log('Connection closed. Has been closed or could not be opened.') } else{ console.log('Unhandled ReadyState: ',this.readyState); } console.log("Disconnected: " + ' reason:' + e.reason + ' was clean:' + e.wasClean + ' code:' + e.code); } //Listen for connection errors ws.onerror = function (e) { console.log("Error: " + e); } //Listen for new messages arriving at the client ws.onmessage = function (e) { console.log("Message received: " + e.data); //Close the socket once one message has arrived ws.close(); } } //Start running the example setup(); })(); 

HTML代码

 <!DOCTYPE html> <html> <head> <title>Websocket Echo Client</title> <meta charset="utf-8"/> </head> <body> <h2>Websocket Echo Client</h2> <div id="output"></div> <input type="file" id="fl"/> <script src="websocket.js"></script> </body> </html> 

服务器代码

 switch (opcode) { case opcodes.TEXT: this.payload = payload.toString("utf8"); winston.log('info','Text:\r\n', this.payload); break; case opcodes.BINARY: console.log('info','File:\r\n', payload.toString("utf8")); 

据我所知在服务器端收到的有效载荷不包含有关文件的元数据。 我相信File对象被视为一个正常的Blob与一些额外的元数据和ws.send只处理它像一个Blob ( 它没有特殊的File处理 )。

元数据可以使用访问

 document.querySelector('input[type="file"]').files[0].name document.querySelector('input[type="file"]').files[0].size document.querySelector('input[type="file"]').files[0].type 

然后分开发送。