【问题标题】:Store files with unique/random names存储具有唯一/随机名称的文件
【发布时间】:2016-09-23 12:05:01
【问题描述】:

借助新的 Firebase API,您可以将文件从客户端代码上传到云存储。 examples 假定文件名在上传期间是已知的或静态的:

// 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');

// 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);

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

【问题讨论】:

    标签: firebase firebase-storage


    【解决方案1】:

    Firebase 存储产品经理在这里:

    TL;DR:使用 UUID 生成器(在 Android (UUID) 和 iOS (NSUUID) 中它们是内置的,在 JS 中你可以使用类似这样的东西:Create GUID / UUID in JavaScript?),然后附加文件扩展名如果你想保留它(在 '.' 上拆分 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
    

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

    【讨论】:

    • 有没有办法使用 web 版本的 firebase 来做到这一点?
    • 一切都很好——我们感谢反馈让产品变得更好。并不是说您的输入无效/这些解决方案是最好的,只是希望它们能够满足大多数开发人员的需求并使产品易于使用和有趣:)
    • 我对 uuid 文档感到困惑。如果生成“基于时间的”uuid,如果同时生成,如何防止两个用户的 uuid 发生冲突?如果生成“随机” uuid,那么两个 uuid 碰撞的可能性不是很小吗?
    • 基于时间的我不确定,但是是的,随机 uuid 可能会发生冲突,但机会很小,几乎是不可能的。
    • 用户 ID + 文件增量 + 现在日期 + 数学随机子字符串 2
    【解决方案2】:

    首先安装uuid - npm i uuid

    然后像这样定义文件引用

    import { v4 as uuidv4 } from "uuid";
    
    const fileRef = storageRef.child(
                `${uuidv4()}-${Put your file or image name here}`
              );
    

    之后,用fileRef的文件上传

    fileRef.put(Your file)

    【讨论】:

      【解决方案3】:

      这是使用飞镖的人的解决方案

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

      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();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-31
        • 1970-01-01
        相关资源
        最近更新 更多