我目前正在创建一个实时聊天应用程序。node.js
这是一个用于后端并用于socket.io
来回连接的 Web 应用程序。
目前,我正在使用个人资料图片创建用户个人资料。这些个人资料图片将存储在一个名为images/profiles/
. 该文件将由用户的id
. 例如:具有id
1 的用户将他们的个人资料图片存储在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
信息发送到服务器。
先感谢您。任何和所有的帮助表示赞赏。