1

I am trying to send image via javascript websockets as binary data

var ws = new WebSocket('ws://127.0.0.1:8000/ws/message/');

var file = document.getElementById('ImageUpload').files[0];
console.log(file)
ws.binaryType = "blob";
ws.send(file)

Using Django channels I am receiving the binary data

from channels.generic.websocket import WebsocketConsumer

class Consumer(WebsocketConsumer):
    def connect(self):
        .....
        .....
        self.accept()

    def receive(self, text_data=None, bytes_data=None):
        if bytes_data:
            # doing some stuffs

How can get the extension(.jpg/.png) of the image file form the binary data which I receive via websocket, can you pleas guide me some suggestion for this, it will be very helpful for me. Thanks in advance.

Ajay Kumar
  • 1,595
  • 3
  • 20
  • 36
  • You won't know the exact file extension unless you include it in the message. Otherwise, you could read the first 2 KiB of the file and use `python-magic` (or similar) to infer the [MIME type](https://www.iana.org/assignments/media-types/media-types.xhtml#image). – Danilo Gómez May 19 '23 at 21:35

1 Answers1

0

you can convert your bytes_data to image by Pillow library in python.take a look at this link: PIL: Convert Bytearray to Image