Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Use a generator function to partition a blob and upload blocks sequentially to Azure Storage
async function putBlocks(blob: Blob, url: string): Promise<string[]> {
const blockIds: string[] = []
let baseUrl = url + '&comp=block'
for (let { block, blockId } of partitionBlob(blob, BLOCK_SIZE)) {
blockIds.push(blockId)
await fetch(`${baseUrl}&blockid=${blockId}`, {
...DEFAULT_FETCH_SETTINGS,
headers: {
'x-ms-blob-type': 'BlockBlob'
},
body: block
})
}
return blockIds
}
function* partitionBlob(blob: Blob, partitionSize: number): Generator<{ block: Blob, blockId: string }, void> {
const totalBlocks = Math.ceil(blob.size / partitionSize)
let blockPointer = 0
for (let blockIndex = 0; blockIndex < totalBlocks; blockIndex++) {
let nextBlockPointer = blockPointer + partitionSize
yield {
block: blob.slice(blockPointer, Math.min(nextBlockPointer, blob.size)),
blockId: getBlockId(blockIndex)
}
blockPointer = nextBlockPointer
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment