node.js的JavaScript文件API如何通过websocket发送带有数据的ArrayBuffer

问题描述 投票:0回答:1

嗨,我正在尝试发送一个文件从JavaScript客户端上传到node.js服务器,它实际上工作,客户端:

var ws = new WebSocket("ws://localhost");
ws.binaryType = "arraybuffer";
//file input code, it all works etc...
loader.onload = (e) {
   ws.send(e.target.result); //actually works and sends the arraybuffer
}
loader.readAsArrayBuffer(file/*not quoted here but you get the idea*/)

服务器端并不重要只是基本的websocket服务器,事实上它实际上是接收arraybuffer(以缓冲区的形式)。

问题:我还需要将文件名和数据一起发送,如何在客户端向ArrayBuffer添加文件头,并在节点中读取它?

javascript node.js websocket buffer fileapi
1个回答
0
投票

你能将ArrayBuffer包装在一个带有文件名或元数据的对象中吗?即

var ws = new WebSocket("ws://localhost");
ws.binaryType = "arraybuffer";

// the object to be passed by the socket
var filePayload = {
    fileName:'file.file',
    fileType:'xxx'
    // any othere metadata here
};

//file input code, it all works etc...
loader.onload = (e) => {
    // add the array buffer as a property in the object
    filePayload['data'] = e.target.result;
    ws.send(filePayload); 
}
loader.readAsArrayBuffer(file/*not quoted here but you get the idea*/)
© www.soinside.com 2019 - 2024. All rights reserved.