Search code examples
htmlserverserver-sent-events

using SSE to send image data


All examples that I have seen that implement server sent events (https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) set content type of the response to text/event-stream.

I was hoping to send image data using the SSE mechanism. But I am not sure if this will work with a text content type.

Can I use SSE for this? Or do I need a "full scale" connection for this?


Solution

  • You could, by base64-encoding the image (SSE does not support sending binary). But (looking at your comment on the other answer that these are large images), don't do that. Assuming the current image generation is timing out because it is slow to generate, not huge, here is how I would do it:

    1. Call /make_my_image/
    2. This is an SSE process, that starts making the image. It sends the usual header.
    3. When the image is ready, save it to local disk (or in an in-memory database, etc.)
    4. Use SSE to send back the URL where the image can be downloaded. Then close the SSE process (server-side).
    5. Client requests the image through Apache (or whatever).
    6. Client could send a message to say when it is has got the image and it can be deleted. And/or use a cron job to clear away old images after so many hours.

    I.e. this plays to SSEs advantage of being good for low-latency text messages: as soon as the image is made the client can download it. Much better than a background process making the image, and then the client has to poll to find out when it is ready.

    If privacy is important - no-one else should be able to download an image - then step 5 could be a PHP (or language of your choice) script that checks the client cookie matches your session, and only streams the file through if so.