Socket io,在聊天应用程序中广播图像而不将它们保存到服务器上的目录中

Socket io, broadcasting images in a chat app without saving them to a directory on the server

我正在使用 socket.io 创建一个聊天应用程序,我需要知道如何以用户身份向“聊天室”中的其他用户广播图像,而无需先将图片保存在一个目录。主要目标是从“文件输入”打开图像并能够将文件 ('picture') 发送给其他用户,以便他们可以在聊天中查看它

从根本上说,使用 FileReader to load the file as a Buffer, then send it. When receiving an image, put its blob into createObjectURL 并创建图像标签。

基本示例 (View Sandbox)

<input type="file" id="img" onchange="setImgSrc(this)" accept="image/*" />
<input type="submit" onclick="submitImg()" />
<div></div>
<!-- OUTPUT DIV -->
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect()

  var src

  var setImgSrc = (elm) => {
    var fr = new FileReader()
    fr.onload = () => (src = fr.result)
    fr.readAsArrayBuffer(elm.files[0])
  }

  var submitImg = () => socket.emit('submitImg', src)

  socket.on('sentImg', (src) => {
    // Create Img...
    var img = document.createElement('img')
    img.src = (window.URL || window.webkitURL).createObjectURL(
      new Blob([src], {
        type: 'image/png'
      })
    )
    img.width = 200
    img.height = 200
    document.querySelector('div').append(img)
  })
</script>
const express = require('express')
const app = express()
const http = require('http').Server(app)
app.use(express.static('src/client'))
const io = require('socket.io')(http)

io.on('connection', (socket) => {
  console.log('Client connected')

  socket.on('submitImg', (src) => {
    console.log('Client sent image')

    //Client submit an image
    io.emit('sentImg', src) //the server send the image src to all clients
  })
})

const port = 8080
http.listen(port, () => {
  console.log('Server Running on Port ' + port)
})