How do I drag an image through SignalR?

  • 0
    Hello everyone.
    I want to send an image from the server (on .net core 3.1), a regular jpg, via SignalR. Get it in the browser, in the angular project and display it on the page.
    A regular text chat works for me.
    What do I do with the image:
    1. On the server I send an image to all (without bothering) clients, an image in byte array format:
    byte[] file = await File.ReadAllBytesAsync(@"C:\Avatars\user7.jpg");
    await Clients.All.BroadCastImage(file);

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

    2. I subscribe to this mailing list 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 + '');
          }
        });
      }


    Working through FileReader is taken from stackerflow, but I also came across a similar description in the tutorial . Also in the process of research I came across the fact that angular may incorrectly process generated urls, added a dependency to the constructor:
    private sanitizer: DomSanitizer

    3. Further, I simply insert this variable into html into the img tag
    & lt; img [src] = "base64data" / & gt;

    4. After sending the image from the server, the broken picture is displayed on the client. Its src contains something that looks like the truth. But then I don't know how to debug it
    JavaScript Gemma Barton, Dec 31, 2018

  • 2 Answers
  • 0
    Who cares, some magic happened here. The fact is that when an array of bytes is sent from c #, it is automatically converted to a base64 string. It took me a while to realize this. I did not find the reasons for this behavior on the Internet, I will be glad if someone tells me.

    In my code, I basically did a double conversion to base64, all this is not necessary, here is the correct code:

    this.connection.on("BroadCastImage", image => {
    this.base64data = this.sanitizer.bypassSecurityTrustUrl('data:image/jpeg;base64,' + image);
    });
    Anonymous

  • 0
    You haven't converted the image to Base64 on the server side.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!