Last active
February 16, 2022 11:48
-
-
Save mraxus/e1e9e4bad4e93320efac2c50b04a39a5 to your computer and use it in GitHub Desktop.
Upload file to s3 with MD5 hash-check
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
const crypt = require('crypto'); | |
const fs = require('fs').promises; | |
const aws = require('aws-sdk'); | |
async function uploadFileToS3WithMd5Hash(bucket, filename, s3Key = null) { | |
const data = await fs.readFile(filename); | |
const md5Base64 = crypt.createHash("md5").update(data).digest('base64'); | |
if (!s3Key) { | |
s3Key = filename; | |
} | |
/** Should you want to get the MD5 in hex format: */ | |
// const md5Hex = Buffer.from(md5Base64, 'base64').toString('hex'); | |
return new Promise((res, rej) => { | |
const s3 = new aws.S3(); | |
s3.putObject({ | |
Bucket: bucket, | |
Key: s3Key, | |
Body: data, | |
ContentMD5: md5Base64, | |
}, (err, resp) => err ? rej(err) : res(resp)); | |
}) | |
} | |
uploadFileToS3WithMd5Hash('your-own-bucket', 'file.txt') | |
.then(console.log) | |
.catch(console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A successful response will be something like
Where ETag is the md5 hash in hex (with quotes around 🤷)