构造给定长度和相同大小的 base 64 字符串

Constructing a base 64 string upto a given length and of same size

我正在阅读本教程 https://www.simple-talk.com/cloud/platform-as-a-service/azure-blob-storage-part-4-uploading-large-blobs/ for implementing a azure method described here https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/put-block

为了实现这个方法,我们需要一个块 ID,它是:

  1. 标识块的有效 Base64 字符串值。
  2. 在编码之前,字符串的大小必须小于或等于 64 个字节。
  3. 对于给定的 blob,为 blockid 参数指定的值的长度必须与每个块的大小相同。

请注意,Base64 字符串必须 URL 编码。

所以为了实现作者说的:

"I usually just number them from 1 to whatever, using a block ID that is formatted to a 7-character string. So for 1, I’ll get “0000001”. Note that block id’s have to be a base 64 string."

并使用此代码:

string blockId = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("BlockId{0}",blockNumber.ToString("0000000"))));

现在,这无疑是 Base64,但她如何满足条件 2 和 3. 因为格式化为“0000000”意味着 23 转换为“0000023”但超过 7 位数字将保持不变,例如“999888777” 违反了 3 个条件,还考虑了 7 个数字,她怎么能 实现一个 64 字节的字符串来满足条件 2.

如果您查看#3,块 ID 必须具有相同的长度。因此,如果您使用:

string blockId = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("BlockId{0}",blockNumber.ToString("0000000"))));

你实质上是说最大的块 ID(或你的情况下的块号)将是 9999999。如果您认为您需要使用超过 7 个字符的块 ID(比如从 100000000 开始的 9 个字符),那么您可以使用如下代码:

string blockId = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("BlockId{0}",blockNumber.ToString("000000000"))));

那么所有的块id都将具有相同的长度。

无论您选择什么序列,只要确保将该序列中的任何数字转换为字符串时,所有数字的长度都必须相同。

我想提及的其他几件事是:

  • 一个 blob 最多可以有 50000 个块。您不能将文件拆分为超过 50,000 个块(块)以将它们作为块上传。
  • 上传块时,您可以按任何顺序上传它们,即您可以先上传块#999,然后再上传块#0。重要的是提交阻止列表的有效负载。构建并保存在 Blob 存储中的最终 Blob 是基于提交块列表中指定的块 ID 顺序。

对我有用的是以下代码(假设块 ID 号是从 0 开始的连续数字):

string blockId = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("BlockId{0}",blockNumber.ToString("d6"))));