嗨,我正在尝试从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(以缓冲区的形式)。
问题: 我还需要将文件 name 与数据一起发送,如何在客户端的ArrayBuffer中添加文件头,并在节点中读取它?
答案 0 :(得分: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*/)