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


I’m creating a chat app with, 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


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()" />
<!-- OUTPUT DIV -->
<script src="/"></script>
  var socket = io.connect()

  var src

  var setImgSrc = (elm) => {
    var fr = new FileReader()
    fr.onload = () => (src = fr.result)

  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
const express = require('express')
const app = express()
const http = require('http').Server(app)
const io = require('')(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