我想将文件上传到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?
您将使用内置的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}`);
作为提示,不建议将new
与Buffer
一起使用,请参阅the documentation。