MD5 hash of a file using javascript

2019-05-24 13:28发布

问题:

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.

回答1:

I got it to work using reader.readAsArrayBuffer():

$(inputElement).change(
    function () {
        var reader = 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: http://crypto-js.googlecode.com/svn/tags/3.1.2/build/components/lib-typedarrays-min.js

jsFiddle here.



回答2:

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.