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 (将#修改为@)