简体   繁体   English

使用javascript的文件的MD5哈希

[英]MD5 hash of a file using javascript

I have to upload a file from the front end and calculate the md5 hash of the file. 我必须从前端上传文件并计算文件的md5哈希值。 I tried to use crypto.js to generate the md5 but for images it is giving me wrong md5. 我试图使用crypto.js生成md5,但对于图像,它给了我错误的md5。 I saw a website called onlinemd5.com and it is exactly what I need. 我看到一个名为onlinemd5.com的网站,这正是我所需要的。

Can anyone help me how to calculate the md5 hash of a file(text file, images, videos etc) using javascript? 谁能帮助我如何使用javascript计算文件(文本文件,图像,视频等)的md5哈希值? Is it possible to download the code from http://onlinemd5.com and implement it? 是否可以从http://onlinemd5.com下载代码并实现它?

Note: I tried some of the suggestions in How to calculate md5 hash of a file using javascript but of no use. 注意:我尝试了一些如何使用javascript计算文件的md5哈希但没有用的建议。


$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. crypto.js没有正确计算图像md5。 I did not try the sparkmd5 js though. 我没有尝试sparkmd5 js。

I got it to work using reader.readAsArrayBuffer() : 我使用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 我不得不从CryptoJS添加一个额外的依赖: http ://crypto-js.googlecode.com/svn/tags/3.1.2/build/components/lib-typedarrays-min.js

jsFiddle here . jsFiddle在这里

I used the spark-md5.js from https://github.com/satazor/SparkMD5 It is awesome and pretty fast. 我使用了来自https://github.com/satazor/SparkMD5的spark-md5.js它非常棒且速度非常快。 This is the best solution if some one is trying to calculate the md5 of any uploaded file. 如果有人试图计算任何上载文件的md5,这是最好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM