How to Transfer Files with Socket.IO?


How to Transfer Files with Socket.IO?

The need for file transfer in real-time web applications is quite common. Socket.IO is built on the WebSocket protocol and offers performance and flexibility in instant data transfer. By developing practical and effective solutions for file transfer with Socket.IO, you can enhance the user experience. In this article, we will explain step by step how to perform file transfer with Socket.IO.

Basic Steps of File Transfer with Socket.IO

When transferring files with Socket.IO, file data is usually transmitted in binary format. In projects working with JavaScript and Node.js, Buffer or ArrayBuffer structures are commonly used. During the transfer process, file data is first taken from the client, then sent to the server with Socket.IO, and afterwards the file is processed on the server or transmitted to other clients.

Receiving Files with Socket.IO on the Server Side

const fs = require('fs');
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server, {
    cors: { origin: '*' }
});
server.listen(3000);

io.on('connection', (socket) => {
    console.log('A user connected.');
    socket.on('file-upload', (data) => {
        // "data" should be in the form { buffer: ..., fileName: ... }
        fs.writeFile(`./uploads/${data.fileName}`, data.buffer, (err) => {
            if (err) {
                socket.emit('upload-status', { success: false, message: 'Upload failed!' });
            } else {
                socket.emit('upload-status', { success: true, message: 'File uploaded successfully.' });
            }
        });
    });
});

Sending Files on the Client Side

const socket = io('http://localhost:3000');

document.getElementById('fileInput').addEventListener('change', function(e) {
    const file = e.target.files[0];
    const reader = new FileReader();
    reader.onload = function(evt) {
        socket.emit('file-upload', {
            buffer: evt.target.result,
            fileName: file.name
        });
    };
    reader.readAsArrayBuffer(file);
});

socket.on('upload-status', function(status) {
    alert(status.message);
});

Things to Consider When Transferring Files with Socket.IO

During file transfer with Socket.IO, attention should be paid to file sizes; very large files should be divided into parts and transmitted. Additionally, for security, controls should be added for file type and content. While uploading files, feedback should be given to the user and notifications should be provided when the transfer is complete.

Conclusion

File transfer with Socket.IO offers a real-time and effective solution. You can use the examples above to add file upload functionality to your application and customize as needed. When configured correctly, fast and secure file transfer is possible with Socket.IO.