safeFilename property

String get safeFilename

Returns a sanitized version of filename safe for use in file paths.

Strips path components, replaces unsafe characters, and preserves only the base name with its extension.

Example: ../../etc/passwdetcpasswd Example: my photo (1).jpgmy_photo_1_.jpg

Implementation

String get safeFilename {
  // Extract only the base name (strip directory traversal)
  final base = p.basename(filename);
  // Get extension separately to preserve it
  final ext = p.extension(base);
  final nameWithoutExt = p.basenameWithoutExtension(base);
  // Replace any non-alphanumeric/dot/hyphen/underscore chars
  final sanitized = nameWithoutExt.replaceAll(RegExp(r'[^a-zA-Z0-9._-]'), '_');
  // Prevent empty filenames
  final safeName = sanitized.isEmpty ? 'upload' : sanitized;
  return '$safeName$ext';
}