receiveFileData method

Future<String?> receiveFileData(
  1. dynamic data,
  2. String tempFileName
)

Receives file data and writes it to disk.

This method handles incoming data, converts it to the appropriate format, and appends it to a file on disk.

data: The incoming data to be written to the file. tempFileName: The name of the file to save the data to.

Implementation

Future<String?> receiveFileData(dynamic data, String tempFileName) async {
  try {
    // Convert data to Uint8List if it isn't already
    Uint8List byteData;
    if (data is Uint8List) {
      byteData = data;
    } else if (data is List<int>) {
      byteData = Uint8List.fromList(data);
    } else {
      debugPrint('Received unsupported data type');
      return null;
    }
    // Get the directory to store the received file
    Directory appDocDirectory = await getApplicationDocumentsDirectory();
    _filePath =
        "${appDocDirectory.path}${Platform.pathSeparator}$tempFileName";
    _file = File(_filePath!);
    _raf = _file.openSync(mode: FileMode.append); // Open file in append mode
    // Append received data to the file
    _raf.writeFromSync(byteData);
    return _filePath; // Return the file path
  } catch (e) {
    debugPrint('Error writing received data to file: $e');
    return null;
  } finally {
    _finalizeFile(); // Ensure the file is finalized after writing
  }
}