存储具有唯一/随机名称的文件

Tra*_*ian 29 firebase firebase-storage

使用新的Firebase API,您可以从客户端代码将文件上传到云存储.这些示例假定文件名在上载期间已知或是静态的:

// Create a root reference
var storageRef = firebase.storage().ref();

// Create a reference to 'mountains.jpg'
var mountainsRef = storageRef.child('mountains.jpg');

// Create a reference to 'images/mountains.jpg'
var mountainImagesRef = storageRef.child('images/mountains.jpg');
Run Code Online (Sandbox Code Playgroud)

要么

// File or Blob, assume the file is called rivers.jpg
var file = ...

// Upload the file to the path 'images/rivers.jpg'
// We can use the 'name' property on the File API to get our file name
var uploadTask = storageRef.child('images/' + file.name).put(file);
Run Code Online (Sandbox Code Playgroud)

用户上传自己的文件时,名称冲突将成为一个问题.如何让Firebase创建文件名而不是自己定义?是否有类似push()数据库中用于创建唯一存储引用的功能?

Mik*_*ald 55

Firebase存储产品经理在这里:

TL; DR:使用UUID生成器(在Android(UUID)和iOS(NSUUID)中内置,在JS中你可以使用这样的东西:在JavaScript中创建GUID/UUID?),然后如果你想要附加文件扩展名保留它(将file.name拆分为'.'并获取最后一段)

我们不知道开发人员想要哪个版本的独特文件(见下文),因为有很多很多用例,所以我们决定将选择留给开发人员.

images/uuid/image.png   // option 1: clean name, under a UUID "folder"
image/uuid.png          // option 2: unique name, same extension
images/uuid             // option 3: no extension
Run Code Online (Sandbox Code Playgroud)

在我看来,这样在我们的文档中解释是合理的,所以我会在内部提交一个bug来记录它:)

  • 这一切都很好 - 我们非常感谢您提供更好的产品反馈.不要试图说你的输入是无效的/这些解决方案是*最好的*,只是希望它们满足大多数开发人员的需求,并使产品使用起来轻松有趣:) (3认同)

Ama*_*ngh 6

这是使用 dart 的人的解决方案

使用以下命令生成当前日期和时间戳:-

var time = DateTime.now().millisecondsSinceEpoch.toString();

现在使用以下命令将文件上传到 firebase 存储:-

await FirebaseStorage.instance.ref('images/$time.png').putFile(yourfile);

您甚至可以使用以下方式获取可下载的网址:-

var url = await FirebaseStorage.instance.ref('images/$time.png').getDownloadURL();