downloadAndSaveFile method

Future<void> downloadAndSaveFile(
  1. String url,
  2. String outputPath,
  3. String fileName,
  4. String extension,
)

Downloads a file from a URL and saves it to the specified path.

Parameters:

  • url: The URL to download the file from
  • outputPath: The directory to save the file in
  • fileName: The name to give the downloaded file
  • extension: The file extension to use

Throws an exception if the download fails or the file cannot be saved.

Implementation

Future<void> downloadAndSaveFile(
  String url,
  String outputPath,
  String fileName,
  String extension,
) async {
  try {
    final response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      final file = File(path.join(outputPath, '$fileName.$extension'));
      await file.writeAsBytes(response.bodyBytes);
      print('File saved: ${file.path}');
    } else {
      throw Exception(
          'Failed to download file. Status code: ${response.statusCode}');
    }
  } catch (e) {
    throw Exception('Error downloading file: $e');
  }
}