fetchVideoToFile function

Future<File> fetchVideoToFile(
  1. String videoUrl,
  2. String filePath
)

Fetches a video from a given URL and saves it to a specified file path.

This function sends an HTTP GET request to the provided videoUrl and streams the response directly into a file at the specified filePath.

Throws an Exception if the HTTP request fails or the response status code is not 200.

Parameters:

  • videoUrl: The URL of the video to be downloaded.
  • filePath: The local file path where the video will be saved.

Returns: A Future that resolves to a File object representing the downloaded video.

Example:

try {
  final file = await fetchVideoToFile(
    'https://example.com/video.mp4',
    '/path/to/save/video.mp4',
  );
  print('Video saved to: ${file.path}');
} catch (e) {
  print('Error downloading video: $e');
}

Implementation

Future<File> fetchVideoToFile(String videoUrl, String filePath) async {
  final request = http.Request('GET', Uri.parse(videoUrl));
  final response = await request.send();

  if (response.statusCode == 200) {
    final file = File(filePath);

    // Create an empty file and open an IOSink to write to it
    final sink = file.openWrite() as IOSink;

    // Pipe the streamed response into the file
    await response.stream.pipe(sink as dynamic);

    // Close the file
    await sink.flush();
    await sink.close();

    return file;
  } else {
    throw Exception('Failed to download video: $videoUrl');
  }
}