file_storage.dart 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import 'dart:io';
  2. import 'dart:typed_data';
  3. import 'package:path_provider/path_provider.dart';
  4. /// 文件存储
  5. class FileStorage {
  6. FileStorage({
  7. required this.directory,
  8. });
  9. /// 存储目录
  10. final String directory;
  11. Future<Uint8List?> read(String fileName) async {
  12. final storagePath = await _getStoragePath();
  13. final filePath = "$storagePath/$fileName";
  14. final file = File(filePath);
  15. if (!await file.exists()) return null;
  16. final text = await file.readAsBytes();
  17. return text;
  18. }
  19. Future<bool> save(String fileName, Uint8List file) async {
  20. final storagePath = await _getStoragePath();
  21. final filePath = "$storagePath/$fileName";
  22. File fileToSave = File(filePath);
  23. _checkAndCreateDir(storagePath);
  24. if (!await fileToSave.exists()) {
  25. try {
  26. fileToSave = await fileToSave.create(recursive: true);
  27. } catch (e) {
  28. print(e);
  29. }
  30. }
  31. await fileToSave.writeAsBytes(file.toList());
  32. return true;
  33. }
  34. Future<bool> delete(String fileName) async {
  35. final storagePath = await _getStoragePath();
  36. final filePath = "$storagePath/$fileName";
  37. final file = File(filePath);
  38. if (await file.exists()) {
  39. try {
  40. await file.delete();
  41. return true;
  42. } catch (e) {
  43. print(e);
  44. return false;
  45. }
  46. }
  47. return false;
  48. }
  49. Future<bool> deleteDirectory(String directoryPath) async {
  50. final storagePath = await _getStoragePath();
  51. final directory = Directory(storagePath);
  52. final result = await directory.exists();
  53. print(directory);
  54. print(result);
  55. if (await directory.exists()) {
  56. try {
  57. await directory.delete(recursive: true);
  58. return true;
  59. } catch (e) {
  60. print(e);
  61. return false;
  62. }
  63. }
  64. return false;
  65. }
  66. Future<void> _checkAndCreateDir(String dir) async {
  67. final directory = Directory(dir);
  68. final parentDirectory = directory.parent;
  69. try {
  70. if (!await parentDirectory.exists()) {
  71. await parentDirectory.create(recursive: true);
  72. }
  73. } catch (e) {
  74. print(e);
  75. }
  76. if (!await directory.exists()) {
  77. try {
  78. await directory.create();
  79. } catch (e) {
  80. print(e);
  81. }
  82. }
  83. }
  84. Future<String> _getStoragePath() async {
  85. Directory? dir;
  86. if (Platform.isAndroid) {
  87. dir = await getExternalStorageDirectory();
  88. }
  89. dir ??= await getApplicationDocumentsDirectory();
  90. if (directory.isNotEmpty) {
  91. return "${dir.path}/$directory";
  92. }
  93. return dir.path;
  94. }
  95. }