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

问题描述:

我一直在为此头疼,我找不到合适的解决方案.我希望能够通过socket.io发射将图像上传到服务器,并在以后将其保存到MongoDB数据库.我该怎么做呢?我见过有人使用base64编码进行编码,但是我无法弄清楚它是如何工作的,该网站上还有其他问题,询问如何通过socket.io从服务器向客户端发送图像,但与此无关.感谢所有帮助.< 3

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. 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. All help is appreciated. <3

目标:使用 socket.emit('image',someimagefile)或类似文件将图像上传到服务器.

Goal: To upload an image to server with socket.emit('image', someimagefile) or similar.

如果您提供类似的方式将图像发送给客户端,我将不胜感激.

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:

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
});

或者更好地使用 FileReader.readAsArrayBuffer 获取要发送到服务器的字节数组.

Or better use FileReader.readAsArrayBuffer to get an array of bytes that you'll send to the server.

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
});