Skip to content

Instantly share code, notes, and snippets.

@igrek8
Created March 20, 2022 10:13
Show Gist options
  • Save igrek8/d362003b6e7b8eb357d36530a6ec4050 to your computer and use it in GitHub Desktop.
Save igrek8/d362003b6e7b8eb357d36530a6ec4050 to your computer and use it in GitHub Desktop.
aws s3 calculate upload parts for multipart
const MIN_CHUNK_SIZE = 5242880; // 5MB in bytes
const DEFAULT_CHUNK_SIZE = 26214400; // 25MB in bytes
export function getUploadParts(contentLength: number, chunkSize: number = DEFAULT_CHUNK_SIZE): string[] {
if (contentLength <= 0) {
throw new Error('ContentLength should be greater than 0 bytes');
}
if (chunkSize < MIN_CHUNK_SIZE) {
throw new Error('ChunkSize should be greater or equal to 5 mb');
}
const chunks = Math.floor(contentLength / chunkSize);
if (chunks <= 1) {
return [`0-${contentLength - 1}`];
}
const parts = [];
const tail = contentLength % chunkSize;
for (let offset = 0; offset < chunks; offset++) {
const start = offset * chunkSize;
const end = (offset + 1) * chunkSize - 1;
const last = offset + 1 === chunks;
parts.push(`${start}-${last ? end + tail : end}`);
}
return parts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment