Skip to content

Instantly share code, notes, and snippets.

@mraxus
Last active February 16, 2022 11:48
Show Gist options
  • Save mraxus/e1e9e4bad4e93320efac2c50b04a39a5 to your computer and use it in GitHub Desktop.
Save mraxus/e1e9e4bad4e93320efac2c50b04a39a5 to your computer and use it in GitHub Desktop.
Upload file to s3 with MD5 hash-check
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);
@mraxus
Copy link
Author

mraxus commented Feb 16, 2022

A successful response will be something like

{
  ETag: '"535aa38d175bdf635b64cd3fa0f43fc6"',
  ...
}

Where ETag is the md5 hash in hex (with quotes around 🤷)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment