如何在js中使用文件的base64编码获取文件的MD5(用于验证s3上传)

问题描述 投票:0回答:1

我想将文件上传到s3,如果我理解正确,s3将向我返回该文件的ETag,这基本上是我已上传文件的md5哈希。我想检查它是否与我的本地哈希相同,以查看其是否正确上传。

但是我找不到使用base64或文件缓冲区获取文件md5的好例子

到目前为止,我有这个:

const result = await s3.putObject({
    Bucket: lambdaConfig.s3BucketName, 
    Key: filePath,
    Body:new Buffer.from(fileBase64,'base64'),
    ContentType: mimeType,
    Metadata: {},
}).promise();

const localHash = // Turn fileBase64 to md5 hash
const remoteHash = JSON.parse(result.ETag);

if( remoteETag === localHash ) {
    // Success.
}

如何从fileBase64获取localHash?

node.js amazon-s3 md5
1个回答
0
投票

您将使用内置的crypto API计算node.js中的哈希。

const crypto = require('crypto');
//...
const etag = crypto.createHash('md5');
// .update means to add to the buffer, you can call .update multiple times
etag.update(Buffer.from(fileBase64, 'base64'));
// .digest(encoding) gives you the computed value of buffer
const localHash = etag.digest('hex');
console.log(`localHash: ${localHash}`);

作为提示,不建议将newBuffer一起使用,请参阅the documentation

© www.soinside.com 2019 - 2024. All rights reserved.