Skip to content

Instantly share code, notes, and snippets.

@guilhermebkel
Last active January 8, 2020 10:07
Show Gist options
  • Save guilhermebkel/373e903e4bfc2559aeb46cccdaa22e3c to your computer and use it in GitHub Desktop.
Save guilhermebkel/373e903e4bfc2559aeb46cccdaa22e3c to your computer and use it in GitHub Desktop.
aws-multipart-upload-nodejs
import * as AWS from "aws-sdk"
import { chunk } from "lodash"
import awsConfig from "config/aws"
const S3 = new AWS.S3(awsConfig.S3)
async function upload(params) {
const { Body, ACL, Bucket, Key, ContentType } = params
const createMultipartUpload = {
ACL,
Bucket,
Key,
ContentType
}
const { UploadId } = await S3.createMultipartUpload(
createMultipartUpload
).promise()
let chunks = []
if (Body.length / 1024 / 1024 >= 5) {
chunks = chunk(Body, 1024 * 1024 * 5)
} else {
chunks = [Body]
}
const chunkUpload: any = {
Bucket,
Key,
UploadId
}
const Parts = await Promise.all(
chunks.map(async (chunk, index) => {
chunkUpload.PartNumber = index + 1
chunkUpload.Body = Buffer.from(chunk)
return {
...(await S3.uploadPart(chunkUpload).promise()),
PartNumber: index + 1
}
})
)
const completeMultipartUpload = {
Bucket,
Key,
UploadId,
MultipartUpload: { Parts }
}
const response = await S3.completeMultipartUpload(
completeMultipartUpload
).promise()
return response
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment