如何解决Node JS服务器中的图像共享
(我是Node js的新手)
我刚刚创建了一个简单的聊天服务,客户端可以将图像发送给其他客户端,但是 该过程非常缓慢,图像的网址太长... 这是我的代码,我正在寻找的是将图像URL发送到服务器,然后将其发送到其他客户端的另一种方法。
客户端:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<input type="file" id="img" onchange="getImgSrc()" accept="image/*">
<input type="submit" onclick="submitImg()">
<div></div> <!-- OUTPUT DIV -->
<script src="/socket.io/socket.io.js"></script>
<script>
const socket=io.connect('http://localhost:80');
var imgFile,fr,src,img;
getImgSrc = () => {
imgFile = document.querySelector('input[type=file]').files[0];
fr = new FileReader();
fr.onload = () => {src = fr.result;} //Get Img Src
fr.readAsDataURL(imgFile);
}
submitImg = () => {
socket.emit('submitImg',src);
}
setImgSize = (img,width,height) => {
img.width = width;
img.height = height;
}
socket.on('sendImg',(src)=>{ // Create Img...
img = document.createElement('img');
img.src = src;
setImgSize(img,200,200);
document.querySelector('div').append(img);
});
</script>
</body>
</html>
服务器端:
const express = require('express');
const app = express();
const http = require('http').Server(app);
app.use(express.static('client'));//index.html folder
const io = require('socket.io')(http);
io.on('connection',(socket) => {
socket.on('submitImg',(src)=>{//Client submit an image
io.emit('sendImg',src); //the server send the image src to all clients
});
});
const port = 80;
http.listen(port,() => {console.log('Server Running on Port ' + port)});
非常感谢,希望您能帮助我。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。