原文地址:file_picker | Flutter Package (flutter-io.cn)
文件选择器
一个允许您使用本机文件资源管理器来选择单个或多个文件的包,支持扩展名过滤。
目前支持的功能
- 使用操作系统默认的原生选择器
- 支持多种平台(移动、Web、桌面和 go-Flutter)
- 使用 自定义格式过滤选择文件——您可以提供文件扩展名列表(pdf、svg、zip 等)
- 从云文件(GDrive、Dropbox、iCloud)中挑选文件
- 支持单个或多个文件选择
- 不同的默认类型过滤器(媒体、图像、视频、音频或其他任意类型)
- 支持选择文件目录
- 如果需要可直接将文件加载到内存 (
Uint8List)中; - 打开一个 保存文件/另存为 对话框(该对话框允许用户指定要保存的文件的驱动器、目录和名称)
如果您有任何希望在此包中看到的功能,请随时提出建议。🎉
兼容图表
| 应用程序接口 | 安卓 | iOS | Linux | 苹果系统 | 视窗 | 网络 |
|---|---|---|---|---|---|---|
| 清除临时文件() | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ |
| 获取目录路径() | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ |
| 选择文件() | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| 保存存档() | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ |
有关详细信息,请参阅File Picker Wiki 的 API 部分或pub.flutter-io.cn 上的官方 API 参考。
文档
有关如何安装、设置和使用它的每个详细信息,请参阅**File Picker Wiki 。**
文件选择器维基
安装
将最新版本的 file_picker 依赖添加到项目 pubspec.yaml 文件中。
用法
快速简单的用法示例:
单个文件
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path);
} else {
// User canceled the picker
}
多个文件
FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true);
if (result != null) {
List<File> files = result.paths.map((path) => File(path)).toList();
} else {
// User canceled the picker
}
注意:result.paths 不支持 Web,Web 只支持以 result.files 的形式获取字节码
具有扩展名过滤器的多个文件
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpg', 'pdf', 'doc'],
);
选择一个目录
String? selectedDirectory = await FilePicker.platform.getDirectoryPath();
if (selectedDirectory == null) {
// User canceled the picker
}
保存文件/另存为对话框
String? outputFile = await FilePicker.platform.saveFile(
dialogTitle: 'Please select an output file:',
fileName: 'output-file.pdf',
);
if (outputFile == null) {
// User canceled the picker
}
加载结果和文件详细信息
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
PlatformFile file = result.files.first;
print(file.name);
print(file.bytes);
print(file.size);
print(file.extension);
print(file.path);
} else {
// User canceled the picker
}
使用 Flutter Web 选择文件并将其上传到 Firebase 存储
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
Uint8List fileBytes = result.files.first.bytes;
String fileName = result.files.first.name;
// Upload file
await FirebaseStorage.instance.ref('uploads/$fileName').putData(fileBytes);
}
有关完整的使用详细信息,请参阅上面的**Wiki**。
示例应用
flutter_file_picker/file_picker_demo.dart at master · miguelpruivo/flutter_file_picker · GitHub
Android

iOS

MacOS

Linux

Windows
