MD5 hash of a file using javascript

痴心易碎 提交于 2019-12-07 19:06:05

问题


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.



来源:https://stackoverflow.com/questions/28437181/md5-hash-of-a-file-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!