想构建一个让用户交流的应用程序?不过用户要的可能不只是文字交谈而已,毕竟一张GIF动图更胜千言万语,用户还可能打算分享视频或其他诸如类型的文件,因此便需要找地方保存做这些文件,Cloud Storage这时就派上用场了
Cloud Storage是非结构化数据所属的托管存储解决方案,因此可用来存储提供链接访问的文件,你可将用户的文件存储到Cloud Storage方便用于与人共享。
Cloud Storage是以存储桶来存储文件的且以文件结构的方式呈现,因此可用目录和子目录来整理文件,使用Cloud Storage就编码而言纯粹就是引用数据桶的位置
path/to/images/dash.gif
要于Cloud Storage上传或下载文件得获取存储桶位置的引用并使用ref方法获取顶级存储桶,然后对该引用套用child方法来导航到子目录,要上传文件的话,需引用包含档名的完整文件路径
final storage = FirebaseStorage.instance.red();
final image = storage.child('images');
final dashImageRef = immage.child('dash.gif');
即便Cloud Storage目前没有这个文件也无妨,这时便可提取本机文件并使用putFile方法来上传
final storage = FirebaseStorage.instance.red();
final images = storage.child('iamges');
final dashImageRef = images.child('dash.gif');
final localFilePath = 'path/to/images/dash.gif';
final file = File(localFilePath);
await dashImageRef.putFile(file);
下载文件的方式也差不多,首先要获取文件的引用以及下载网址,这样便能透过网址显示图像,方法就跟在Flutter中显示其他网络图像一样
final storage = FirebaseStorage.instance.ref();
final images = storage.child('images');
final dashImageRef = images.child('dash.git');
final newwotkImageUrl = await dashImageRef.getDownloadURL();
// ...
Widget build(Context context) {
return Container(
child: Image.network(networkImageUrl),
);
}
// ...
还可下载文件或其列表数据并存储为本机或内存档案
若只想与特定用户共享文件,可利用认证机制Firebase Authentication以及Cloud Storage的Firebase安全规则来保护文件。
最棒的是Cloud Storage有免费方案方便各位今天就开始用。
想多加了解Cloud Storage以及其他各项软件包,请参考pub.dev
原文翻译自视频:视频地址