0

我目前正在创建一个实时聊天应用程序。node.js这是一个用于后端并用于socket.io来回连接的 Web 应用程序。

目前,我正在使用个人资料图片创建用户个人资料。这些个人资料图片将存储在一个名为images/profiles/. 该文件将由用户的id. 例如:具有id1 的用户将他们的个人资料图片存储在images/profiles/1.png. 非常不言自明。

当用户提交表单以更改他们的头像时,浏览器 JavaScript 将获取图像,并将其发送到服务器:

form.addEventListener('submit', handleForm)

function handleForm(event) {
  event.preventDefault(); // stop page from reloading

  let profilePicture; // set variable for profile picture
  let profilePictureInput = document.getElementById('profilePictureInput'); // get image input

  const files = profilePictureInput.files[0]; // get input's files

  if (files) {
    const fileReader = new FileReader(); // initialize file reader

    fileReader.readAsDataURL(files);
    fileReader.onload = function () {
      profilePicture = this.result; // put result into variable

      socket.emit("request-name", {
        profilePicture: profilePicture,
        id: userID,
      }); // send result, along with user id, to server
  }
}

我已经注释了大部分代码,所以很容易理解。然后服务器获取此信息。有了这些信息,服务器应该将发送的图像转换为一种png格式(我可以做任何格式,但所有图像的格式必须相同)。我目前正在使用该jimp库来执行此任务,但它似乎不起作用。

const jimp = require('jimp'); // initialize Jimp

socket.on('request-name', (data) => { // when request has been received
  // read the buffer from image (I'm not 100% sure what Buffer.from() does, but I saw this online)
  jimp.read(Buffer.from(data.profilePicture), function (error, image) {
    if (error) throw error; // throw error if there is one

    image.write(`images/profiles/${data.id}.png`); // write image to designated place
  }
});

我得到的错误:

Error: Could not find MIME for Buffer <null>

我已经在互联网上搜索了答案,但找不到任何答案。如果有帮助,我可以使用另一个库。我还可以更改文件格式(如果需要,可以更改.png.jpg.jpeg;它只需要与所有文件保持一致)。我唯一不能改变的是使用 JavaScript/Node.js并将socket.io信息发送到服务器。

先感谢您。任何和所有的帮助表示赞赏。

4

1 回答 1

0

如果您只是将数据 URI 作为字符串获取,那么您可以使用它构造一个缓冲区,然后使用内置函数fs来写入文件。确保相对路径准确。

socket.on('request-name', data => {
  const imgBuffer = Buffer.from(data.profilePicture, 'base64');
  fs.writeFile(`images/profiles/${data.id}.png`, imgBuffer);
}
于 2022-01-24T01:36:48.280 回答