Last active
January 8, 2020 10:07
-
-
Save guilhermebkel/373e903e4bfc2559aeb46cccdaa22e3c to your computer and use it in GitHub Desktop.
aws-multipart-upload-nodejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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