简体   繁体   English

如何通过 socket.io 将图像发送到服务器?

[英]How do I send image to server via socket.io?

I've been beating my head over this and I can't find a proper solution.我一直在为此烦恼,但找不到合适的解决方案。 I want to be able to upload images to the server via socket.io emit and save them to a MongoDB database later.我希望能够通过 socket.io 发射将图像上传到服务器,并稍后将它们保存到 MongoDB 数据库中。 How do I do this?我该怎么做呢? I've seen people doing it with base64 encoding but I can't figure out how that exactly works, there are other questions on this website asking about sending an image to client from server via socket.io but none about this.我见过有人用 base64 编码做这件事,但我不知道它到底是如何工作的,这个网站上还有其他问题,询问通过 socket.io 从服务器向客户端发送图像,但没有关于这一点。 All help is appreciated.感谢所有帮助。 <3 <3

Goal: To upload an image to server with socket.emit('image', someimagefile) or similar.目标:使用socket.emit('image', someimagefile)或类似方法将图像上传到服务器。

I'd really appreciate if you provide a similar way to send an image to the client.如果您提供类似的方式向客户端发送图像,我将不胜感激。

As you mentioned, you can convert the image to base64 using FileReader.readAsDataURL and send the encoded string, and decode it on the server:正如您所提到的,您可以使用FileReader.readAsDataURL将图像转换为base64并发送编码字符串,然后在服务器上对其进行解码:

document.getElementById('file').addEventListener('change', function() {

  const reader = new FileReader();
  reader.onload = function() {
    const base64 = this.result.replace(/.*base64,/, '');
    socket.emit('image', base64);
  };
  reader.readAsDataURL(this.files[0]);

}, false);
socket.on('image', async image => {
    const buffer = Buffer.from(image, 'base64');
    await fs.writeFile('/tmp/image', buffer).catch(console.error); // fs.promises
});

Or better use FileReader.readAsArrayBuffer to get an array of bytes that you'll send to the server.或者更好地使用FileReader.readAsArrayBuffer来获取您将发送到服务器的字节数组。

document.getElementById('file').addEventListener('change', function() {

  const reader = new FileReader();
  reader.onload = function() {
    const bytes = new Uint8Array(this.result);
    socket.emit('image', bytes);
  };
  reader.readAsArrayBuffer(this.files[0]);

}, false);
socket.on('image', async image => {
    // image is an array of bytes
    const buffer = Buffer.from(image);
    await fs.writeFile('/tmp/image', buffer).catch(console.error); // fs.promises
});

To receive from the server:从服务器接收:

// Server side
socket.emit('image', image.toString('base64')); // image should be a buffer
// Client side
socket.on('image', image => {
    // create image with
    const img = new Image();
    // change image type to whatever you use, or detect it in the backend 
    // and send it if you support multiple extensions
    img.src = `data:image/jpg;base64,${image}`; 
    // Insert it into the DOM
});

i don't know if any one is looking for it anymore but I made possible to send media via socket.io... here is the code:我不知道是否有人在寻找它,但我可以通过 socket.io 发送媒体......这是代码:

// sending media from client side
$("#send_media").change(function (e) {
  var data = e.originalEvent.target.files[0];
  var reader = new FileReader();
  reader.onload = function (evt) {
    var msg = {};
    msg.file = evt.target.result;
    msg.fileName = data.name;
    socket.emit("base64 file", msg);
    console.log(msg)
  };
  reader.readAsDataURL(data);
});
   
// showing media to ui 
socket.on("base64 image", (msg) => {
  console.log("as", msg);
  $(".messages")
    .append(`<img src=${msg.file} alt="Red dot" />`);

  scrollToBottom();
});

// sending media from server side
    socket.on("base64 file", function (msg) {
      console.log("received base64 file from server: " + msg.fileName);
      socket.username = msg.username;
      io.to(roomId).emit('base64 image', //exclude sender
      // io.sockets.emit(
      //   "base64 file", //include sender

        {
          file: msg.file,
          fileName: msg.fileName,
        }
      );
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM