问题
Uploading file in chunks using Blob API. Here I want to check the md5 checksum of the blob. When I tried the below code it is working fine for text files, but it is returning different value for binary files.
var reader = new FileReader();
reader.readAsBinaryString(blob);
reader.onloadend = function () {
var mdsum = CryptoJS.MD5(reader.result);
console.log("MD5 Checksum",mdsum.toString());
};
How to calculate the md5 checksum of blob correctly for all types of files ?
回答1:
Use the following code to create a correct md5 hash:
function calculateMd5(blob, callback) {
var reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onloadend = function () {
var wordArray = CryptoJS.lib.WordArray.create(reader.result),
hash = CryptoJS.MD5(wordArray).toString();
// or CryptoJS.SHA256(wordArray).toString(); for SHA-2
console.log("MD5 Checksum", hash);
callback(hash);
};
}
Update (a bit simpler):
function calculateMd5(blob, callback) {
var reader = new FileReader();
reader.readAsBinaryString(blob);
reader.onloadend = function () {
var hash = CryptoJS.MD5(reader.result).toString();
// or CryptoJS.SHA256(reader.result).toString(); for SHA-2
console.log("MD5 Checksum", hash);
callback(hash);
};
}
Be sure to include core.js
, lib-typedarrays.js
(important) and md5.js
components from CryptoJS library.
Please see this fiddle for a complete example (because of origin access control it won't work on fiddle, try it on your local server).
来源:https://stackoverflow.com/questions/34492637/how-to-calculate-md5-checksum-of-blob-using-cryptojs