sendFile method

Future<void> sendFile(
  1. String filePath
)

send file partial download 206

Implementation

Future<void> sendFile(String filePath) async {
  try {
    final file = File(filePath);
    final name = file.path.split('/').last;
    final fileLength = file.lengthSync();

    if (file.existsSync()) {
      final rangeHeader = headers.value(HttpHeaders.rangeHeader);
      if (rangeHeader != null) {
        // partial download 206 အတွက်
        // Example: Range: bytes=1000-
        final match = RegExp(r"bytes=(\d+)-(\d*)").firstMatch(rangeHeader);
        final start = int.parse(match!.group(1)!);
        final end = match.group(2)!.isNotEmpty
            ? int.parse(match.group(2)!)
            : fileLength - 1;

        final chunkSize = end - start + 1;

        response
          ..statusCode = HttpStatus.partialContent
          ..headers.add(
            HttpHeaders.contentTypeHeader,
            "application/octet-stream",
          )
          ..headers.add(HttpHeaders.acceptRangesHeader, "bytes")
          ..headers.add(
            HttpHeaders.contentRangeHeader,
            "bytes $start-$end/$fileLength",
          )
          ..headers.add(HttpHeaders.contentLengthHeader, chunkSize)
          ..headers.set(
            'Content-Disposition',
            'attachment; filename="${TEncoder.encodeRFC5987(name)}"',
          );

        final raf = file.openSync();
        raf.setPositionSync(start);
        response.add(raf.readSync(chunkSize));
        await response.close();
        raf.close();
      } else {
        // full file send
        response.headers.set('Content-Type', 'text/plain; charset=utf-8');
        response.headers.set(
          'Content-Disposition',
          'attachment; filename="${TEncoder.encodeRFC5987(name)}"',
        );
        response.headers.set('Content-Length', fileLength);

        // UTF-8 stream နဲ့ pipe လုပ်
        await file.openRead().pipe(response);
      }
    } else {
      response
        ..statusCode = HttpStatus.notFound
        ..write('File not found')
        ..close();
    }
  } catch (e) {
    TLogger.instance.showLog(e.toString(), tag: 'sendFile');
    response
      ..statusCode = HttpStatus.internalServerError
      ..write('Server Error')
      ..close();
  }
}