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 ?
Open a terminal window. Type the following command: md5sum [type file name with extension here] [path of the file] -- NOTE: You can also drag the file to the terminal window instead of typing the full path. Hit the Enter key. You'll see the MD5 sum of the file.
md5sum is used to verify the integrity of files, as virtually any change to a file will cause its MD5 hash to change. Most commonly, md5sum is used to verify that a file has not changed as a result of a faulty file transfer, a disk error or non-malicious meddling.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With