In the last post I talked about streaming data back via a WebAPI. On the front end, I had a “download” button that I wanted to disable until the download is complete, so that users don’t inadvertently spam the server with download requests. When the button is clicked, an iframe is opened to the WebAPI address, causing the file to download. The problem is that I don’t know when the download is complete. Chrome doesn’t raise events in an iframe, so you can’t rely on that.
Luckily, since I have a SignalR connection, I can notify the client about the file’s download completion once the stream is closed… if I can figure that out.
Aside
There’s probably a more elegant way to do this with middleware, but this worked and wasn’t too bad.
Extending MemoryStream
MemoryStream is made to be extensible (as it is the base class for several different streams), so we can easily hook in to it and raise an event when the Dispose method is invoked:
So now we can pass an action to call out to the Hub to send the message we need once the stream is closed.