Reputation: 604
I have to upload a file from the front end and calculate the md5 hash of the file. I tried to use crypto.js to generate the md5 but for images it is giving me wrong md5. I saw a website called onlinemd5.com and it is exactly what I need.
Can anyone help me how to calculate the md5 hash of a file(text file, images, videos etc) using javascript? Is it possible to download the code from http://onlinemd5.com and implement it?
Note: I tried some of the suggestions in How to calculate md5 hash of a file using javascript but of no use.
$scope.upld = function(element){
$scope.files = element.files;
var file = $scope.files[0];
var reader = new FileReader();
reader.onload = function(){
$scope.md5_val = CryptoJS.MD5(reader.result);
$scope.upload_file();
$scope.$apply();
};
reader.readAsBinaryString(file);
};
The crypto.js is not calculating the image md5 correctly. I did not try the sparkmd5 js though.
Upvotes: 3
Views: 13907
Reputation: 7880
I got it to work using reader.readAsArrayBuffer()
:
$(inputElement).change(
function () {
var reader = new FileReader();
reader.addEventListener(
'load',
function () {
var wordArray = CryptoJS.lib.WordArray.create(this.result);
console.log(CryptoJS.MD5(wordArray));
}
);
reader.readAsArrayBuffer(this.files[0]);
}
);
I had to add an extra dependency from CryptoJS: https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js
Upvotes: 7
Reputation: 604
I used the spark-md5.js from https://github.com/satazor/SparkMD5 It is awesome and pretty fast. This is the best solution if some one is trying to calculate the md5 of any uploaded file.
Upvotes: 5