socket io, node js, Simple example to send image/files from server to client

前端 未结 1 500
独厮守ぢ
独厮守ぢ 2020-12-12 12:10

Is there any plain and straight forward examples on how to serve an image? from server to client? through buffering or just a direct call to download? (the goal is to get i

相关标签:
1条回答
  • 2020-12-12 12:44

    One possible solution is to base64-encode the image data and use that in the browser via image.src:

    On the server side, try changing this:

    socket.emit('image', { image: true, buffer: buf });
    

    to this:

    socket.emit('image', { image: true, buffer: buf.toString('base64') });
    

    Then on the client side:

    var ctx = document.getElementById('canvas').getContext('2d');
    
    // ...
    
    socket.on("image", function(info) {
      if (info.image) {
        var img = new Image();
        img.src = 'data:image/jpeg;base64,' + info.buffer;
        ctx.drawImage(img, 0, 0);
      }
    });
    
    0 讨论(0)
提交回复
热议问题