53 lines
1.5 KiB
Dart
53 lines
1.5 KiB
Dart
import 'dart:io';
|
|
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:open_filex/open_filex.dart';
|
|
import 'package:path_provider/path_provider.dart';
|
|
|
|
import 'download_result.dart';
|
|
import 'file_download_common.dart';
|
|
|
|
Future<DownloadResult> downloadFileFromUrlImpl(
|
|
String url, {
|
|
String? fileName,
|
|
Map<String, String>? headers,
|
|
bool openAfterDownload = false,
|
|
}) async {
|
|
try {
|
|
final response = await http.get(Uri.parse(url), headers: headers);
|
|
if (response.statusCode != 200) {
|
|
return DownloadResult.failure(
|
|
'Download failed (${response.statusCode})',
|
|
);
|
|
}
|
|
|
|
final name = fileName ?? fileNameFromUrl(url);
|
|
final dir = await _resolveSaveDirectory();
|
|
final file = File('${dir.path}/$name');
|
|
await file.writeAsBytes(response.bodyBytes, flush: true);
|
|
|
|
if (openAfterDownload) {
|
|
await OpenFilex.open(file.path);
|
|
}
|
|
|
|
return DownloadResult.success(
|
|
savedPath: file.path,
|
|
message: openAfterDownload ? 'E-Card downloaded' : 'E-Card saved',
|
|
);
|
|
} catch (e) {
|
|
return DownloadResult.failure('Could not download file');
|
|
}
|
|
}
|
|
|
|
Future<Directory> _resolveSaveDirectory() async {
|
|
if (Platform.isAndroid) {
|
|
final downloads = await getDownloadsDirectory();
|
|
if (downloads != null) return downloads;
|
|
}
|
|
if (Platform.isIOS) {
|
|
return getApplicationDocumentsDirectory();
|
|
}
|
|
final downloads = await getDownloadsDirectory();
|
|
return downloads ?? await getApplicationDocumentsDirectory();
|
|
}
|