i have implemented the functionality of the send image like this using socket.io here is my code block of that.
socket.on("send-image", async (data) => {
const { image, room } = data;
try {
const savedImage = await prisma.image.create({
data: {
imageUrl: image,
room: room,
},
});
io.to(room).emit("new-image", {
type: "image",
image: savedImage.imageUrl, // Send the saved image URL
});
//socket.to(room).emit('receive-message', { type: 'image', image: savedImage.imageUrl });
console.log(`Only Image saved and emitted to room ${room}`);
} catch (error) {
console.error("Error saving image to database:", error);
}
});
in frontend i have implemented following function to handle it is working fine
const handleImageUpload = () => {
if (image) {
const reader = new FileReader();
reader.onloadend = () => {
const base64String = reader.result as string; // Convert to string
socket.emit("send-image", { type: 'image', image: base64String, room });
setImage(null);
};
reader.readAsDataURL(image); // Convert image to base64
}
};
const base64ToBlobUrl = (base64: string) => {
const byteCharacters = atob(base64.split(',')[1]);
const byteNumbers = new Uint8Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const blob = new Blob([byteNumbers], { type: 'image/png' });
return URL.createObjectURL(blob);
};
but now i have implemented same kind of functions for the video and document in socket.io
// Socket event listener for sending a video message
socket.on("send-video", async (data) => {
const { videoUrl, room } = data;
try {
// Save the video URL to your database using Prisma
const savedVideo = await prisma.video.create({
data: {
videoUrl: videoUrl,
room: room,
},
});
// Emit the new video message to all clients in the room
io.to(room).emit("new-video", {
type: "video",
videoUrl: savedVideo.videoUrl, // Send the saved video URL
});
console.log(`Only Video saved and emitted to room ${room}`);
} catch (error) {
console.error("Error saving video to database:", error);
}
});
socket.on("send-document", async (data) => {
const { documentUrl, room } = data;
try {
// Save the document URL to your database using Prisma
const savedDocument = await prisma.document.create({
data: {
documentUrl: documentUrl,
room: room,
},
});
// Emit the new document message to all clients in the room
io.to(room).emit("new-document", {
type: "document",
documentUrl: savedDocument.documentUrl, // Send the saved document URL
});
console.log(`Only Document saved and emitted to room ${room}`);
} catch (error) {
console.error("Error saving document to database:", error);
}
});
what changes now i have to make from frontend to implement the these two functions also is there any problem with conversion of base64
Arnav Sharma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.