V
V
Victor P.2020-11-08 23:07:18
JavaScript
Victor P., 2020-11-08 23:07:18

How to push an image through SignalR?

Hello.
I want to send an image from the server (on .net core 3.1), the usual jpg, via SignalR. Get it in the browser, in the angular project and display it on the page.
The usual text chat works for me.
What I do with the image:
1. On the server, I send the image to all (without bothering) clients, the image is in byte array format:

byte[] file = await File.ReadAllBytesAsync(@"C:\Avatars\user7.jpg");
await Clients.All.BroadCastImage(file);

The file exists, some real array of bytes appears in the file variable.

2. I subscribe to this newsletter on the client in Angular:
// стандартные подключения
  public initConnection() {
    this.connection = new signalR.HubConnectionBuilder()
      .withUrl('/chat')
      .build();
  }

  public connectionWebSocket() {
    this.connection.start();

    this.connection.on("BroadCastImage", image => {
      var blob = new Blob([image], { type: "image/jpeg" });
      var reader = new FileReader();
      reader.readAsDataURL(blob);
      var that = this;
      reader.onloadend = function () {
        that.base64data = that.sanitizer.bypassSecurityTrustUrl(reader.result + '');
      }
    });
  }


Work through FileReader is taken from stackoverflow, but I also came across a similar description in the textbook . Also, in the process of research, I came across the fact that Angular can incorrectly process generated urls, added a dependency to the constructor:
private sanitizer: DomSanitizer

3. Then I simply insert this variable into html in the img tag 4. After sending the image from the server, a broken image is displayed on the client. In its src is something that looks like the truth. But then I don't know how to fix it.
<img [src]="base64data"/>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
Johnny Gat, 2020-11-09
@Jeer

You didn't convert the image to Base64 on the server side.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question