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

Issue

I’m creating a chat app with socket.io, i need to know, how i can broadcast images as a user to other users in the "chat room" without the need to first save the picture in a directory. The main goal is to open the image from a "file input" and be able to send the file (‘picture’) to other users so they can view It in the chat

Solution

Fundamentally, use FileReader to load the file as a Buffer, then send it. When receiving an image, put its blob into createObjectURL and create an image tag.

Basic Example (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)
})

Answered By – Lawrence Cherone

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published