websocket写起来很优雅(对于你一句我一句的HTTP来说),写的小项目有传输图片的需求,单独拎出来记录一下。
后端Node.js
websocket.js
配置了跨域,前端传来了文件直接通过回调返回回去。
const io = require("socket.io");
module.exports = (httpServer) => {
const server = io(httpServer, { cors: true });
server.on("connection", (socket) => {
socket.on("image_upload", (file, callback) => {
callback(file);
});
});
};
前端
index.html
<html lang="en">
<head>
<!-- socket.io -->
<script src="https://cdn.socket.io/4.3.2/socket.io.min.js"
integrity="sha384-KAZ4DtjNhLChOB/hxXuKqhMLYvx3b5MlT55xPEiNmREKRzeEm+RVPlTnAn0ajQNs"
crossorigin="anonymous"></script>
</head>
<body>
<input type="file" value="上传图片">
<div class="image-container"></div>
</body>
<script>
function arrayBufferToBase64(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
const file = document.querySelector('input[type=file]')
// 连接websocket
const socket = io("ws://localhost:3000");
// 选择文件上传
file.onchange = function (e) {
// 向服务器发送图片二进制文件
socket.emit("image_upload", e.target.files[0], show)
}
// 处理服务器返回的图片二进制数据
function show(file) {
console.log(file); // ArrayBuffer[10000]
// 将二进制流转换成base64插入到html中
const img = document.createElement('img')
img.src = 'data:image/jpeg;base64,' + (arrayBufferToBase64(file));
document.querySelector('.image-container').appendChild(img)
})
</script>
</html>