[英]How to save incoming textfile from client from websocket connection
我正在嘗試在不使用任何框架的情況下在node.js中實現websocket服務器。 從客戶端向服務器發送消息運行正常。 但是現在我嘗試將文本文件從客戶端發送到服務器。 通過使用終端中的console.log,我可以在服務器端看到內容。 但:
我如何獲取文件信息? (名稱,創建/編輯日期等?)
如何保存文件?
客戶代碼:
(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
然后分別發送。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.