如何在 firebase 存储中上传 PDF 文件并生成下载 URL 并使用 Flutter 保存 firebase?
How can I upload PDF file in firebase storage and generate download URL and save firebase using Flutter?
我尝试了下面的代码但遇到了问题:
Unhandled Exception: Null check operator used on a null value
FirebaseStorage storage = FirebaseStorage.instance;
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
withData: true
);
if (result != null) {
Uint8List? fileBytes = result.files.first.bytes;
String fileName = result.files.first.name;
// Upload PDF file
TaskSnapshot taskSnapshot = await storage.ref('CV/$fileName').putData(fileBytes!);
String pdfUrl = await taskSnapshot.ref.getDownloadURL();
print('pdf url: $pdfUrl');
}
您收到错误消息是因为 fileBytes
变量在运行时为空,而您在其上使用了空检查运算符。
选择文件中出现空字节的原因是因为默认情况下,pickFiles 方法不返回字节数据(web 除外)。您需要将 withData
设置为 true
并且 null 错误应该消失。
If withData is set, picked files will have its byte data immediately
available on memory as Uint8List which can be useful if you are
picking it for server upload or similar. However, have in mind that
enabling this on IO (iOS & Android) may result in out of memory issues
if you allow multiple picks or pick huge files. Use withReadStream
instead. Defaults to true on web, false otherwise.
将您的代码更新为:
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
withData: true
);
我尝试了下面的代码但遇到了问题:
Unhandled Exception: Null check operator used on a null value
FirebaseStorage storage = FirebaseStorage.instance;
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
withData: true
);
if (result != null) {
Uint8List? fileBytes = result.files.first.bytes;
String fileName = result.files.first.name;
// Upload PDF file
TaskSnapshot taskSnapshot = await storage.ref('CV/$fileName').putData(fileBytes!);
String pdfUrl = await taskSnapshot.ref.getDownloadURL();
print('pdf url: $pdfUrl');
}
您收到错误消息是因为 fileBytes
变量在运行时为空,而您在其上使用了空检查运算符。
选择文件中出现空字节的原因是因为默认情况下,pickFiles 方法不返回字节数据(web 除外)。您需要将 withData
设置为 true
并且 null 错误应该消失。
If withData is set, picked files will have its byte data immediately available on memory as Uint8List which can be useful if you are picking it for server upload or similar. However, have in mind that enabling this on IO (iOS & Android) may result in out of memory issues if you allow multiple picks or pick huge files. Use withReadStream instead. Defaults to true on web, false otherwise.
将您的代码更新为:
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
withData: true
);