saveToDownloads static method

Future<String?> saveToDownloads({
  1. required String sourcePath,
  2. required String fileName,
  3. String? mimeType,
  4. String? subfolder,
})

Copies a local file into the Downloads folder (Android: public Downloads; desktop: ~/Downloads); null on iOS/web. await UFile.saveToDownloads(sourcePath: p, fileName: "a.pdf")

Implementation

static Future<String?> saveToDownloads({required String sourcePath, required String fileName, String? mimeType, String? subfolder}) async {
  if (kIsWeb || Platform.isIOS) return null;
  if (Platform.isAndroid) return UFilesChannel.saveToDownloads(sourcePath: sourcePath, fileName: fileName, mimeType: mimeType, subfolder: subfolder);
  // Desktop: copy into the user's Downloads folder, adding " (1)", " (2)"… instead of overwriting.
  final Directory? downloads = await getDownloadsDirectory();
  if (downloads == null) return null;
  final Directory folder = Directory(subfolder == null ? downloads.path : path.join(downloads.path, subfolder));
  await folder.create(recursive: true);
  final String base = path.basenameWithoutExtension(fileName);
  final String ext = path.extension(fileName);
  String target = path.join(folder.path, fileName);
  for (int i = 1; File(target).existsSync(); i++) {
    target = path.join(folder.path, "$base ($i)$ext");
  }
  await File(sourcePath).copy(target);
  return target;
}