sendFileToServer method
Sends a file over the WebSocket connection in chunks.
This method reads the specified file from disk in chunks of 64 KB and sends each chunk over the WebSocket connection to the server. The method ensures that large files are handled efficiently by sending them in manageable chunks.
filePath: The path of the file to be sent.
Returns true if the file was successfully sent, false if the file was not found.
Implementation
Future<bool> sendFileToServer(String filePath) async {
if (_socket != null) {
final file = File(filePath);
if (await file.exists()) {
const chunkSize = 64 * 1024; // 64 KB per chunk
final raf = file.openSync(mode: FileMode.read);
int totalBytesSent = 0;
try {
while (true) {
final chunk = raf.readSync(chunkSize);
if (chunk.isEmpty) break; // Exit loop if no more data to read
_socket!.add(chunk); // Send chunk over WebSocket
totalBytesSent += chunk.length; // Track total bytes sent
debugPrint('Sent chunk of size: ${chunk.length} bytes');
}
} finally {
raf.closeSync(); // Ensure the file is closed after reading
}
debugPrint('Total bytes sent: $totalBytesSent');
debugPrint('File sending completed.');
return true;
} else {
debugPrint('File not found: $filePath');
return false;
}
} else {
debugPrint('No connection to send message.');
return false;
}
}