使用文件选择器将 PlatformFile 制作成 Flutter 中的文件
Make PlatformFile into File in Flutter using File Picker
我正在使用文件选择器插件从设备中选择文件。该文件是在 PlatformFile 的数据类型中选择的,但我想将该文件发送到 Firebase 存储,为此我需要一个常规文件。如何将 PlatformFile 转换为文件以便将其发送到 Firebase 存储?这是代码:
PlatformFile pdf;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
void _trySubmit() async {
final isValid = _formKey.currentState.validate();
if (isValid) {
_formKey.currentState.save();
final ref = FirebaseStorage.instance
.ref()
.child('article_pdf')
.child(title + '-' + author + '.pdf');
await ref.putFile(pdf).onComplete; // This throws an error saying that The argument type 'PlatformFile' can't be assigned to the parameter type 'File'
}
}
void _pickFile() async {
FilePickerResult result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
);
if (result != null) {
pdf = result.files.first;
}
}
试试这个:
PlatformFile pdf;
final File fileForFirebase = File(pdf.path);
编码愉快! :)
如果您使用的是网络应用程序,则可以 post 使用 flutter_file_picker 将图像文件上传到 Firestore:(摘自常见问题解答页面):https://github.com/miguelpruivo/flutter_file_picker/wiki/FAQ
// get file
final result = await FilePicker.platform.pickFiles(type: FileType.any, allowMultiple:
false);
if (result.files.first != null){
var fileBytes = result.files.first.bytes;
var fileName = result.files.first.name;
// upload file
await FirebaseStorage.instance.ref('uploads/$fileName').putData(fileBytes);
}
我正在使用文件选择器插件从设备中选择文件。该文件是在 PlatformFile 的数据类型中选择的,但我想将该文件发送到 Firebase 存储,为此我需要一个常规文件。如何将 PlatformFile 转换为文件以便将其发送到 Firebase 存储?这是代码:
PlatformFile pdf;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
void _trySubmit() async {
final isValid = _formKey.currentState.validate();
if (isValid) {
_formKey.currentState.save();
final ref = FirebaseStorage.instance
.ref()
.child('article_pdf')
.child(title + '-' + author + '.pdf');
await ref.putFile(pdf).onComplete; // This throws an error saying that The argument type 'PlatformFile' can't be assigned to the parameter type 'File'
}
}
void _pickFile() async {
FilePickerResult result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
);
if (result != null) {
pdf = result.files.first;
}
}
试试这个:
PlatformFile pdf;
final File fileForFirebase = File(pdf.path);
编码愉快! :)
如果您使用的是网络应用程序,则可以 post 使用 flutter_file_picker 将图像文件上传到 Firestore:(摘自常见问题解答页面):https://github.com/miguelpruivo/flutter_file_picker/wiki/FAQ
// get file
final result = await FilePicker.platform.pickFiles(type: FileType.any, allowMultiple:
false);
if (result.files.first != null){
var fileBytes = result.files.first.bytes;
var fileName = result.files.first.name;
// upload file
await FirebaseStorage.instance.ref('uploads/$fileName').putData(fileBytes);
}