每个文件的md5值都是唯一的,这也是很多下载网站,会告诉你原文件的md5是多少,然后下载完毕让你自行去对比是否一致,以检验文件是否是完整的。校验md5亦可实现所谓的”秒传“功能。
使用到的类库 Spark-MD5
- function getMD5(file, callBack) {
- /*
- * file 选取的文件
- * callBack 回调函数可以返回获取的MD5
- */
- let fileReader = new FileReader(),
- blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice,
- chunkSize = 2097152,
- // read in chunks of 2MB
- chunks = Math.ceil(file.size / chunkSize),
- currentChunk = 0,
- spark = new SparkMD5();
- fileReader.onload = function (e) {
- spark.appendBinary(e.target.result); // append binary string
- currentChunk++;
- if (currentChunk < chunks) {
- loadNext();
- }
- else {
- callBack(spark.end());
- }
- };
- function loadNext() {
- let start = currentChunk * chunkSize,
- end = start + chunkSize >= file.size ? file.size : start + chunkSize;
- fileReader.readAsBinaryString(blobSlice.call(file, start, end));
- };
- loadNext();
- };
完整例子:
- <!DOCTYPE html>
- <html>
- <head>
- <title>speak-MD5</title>
- </head>
- <body>
- <input type=“file” name=“” id=‘file’>
- <script type=“text/javascript” src=“js/jquery.js”></script>
- <script type=“text/javascript” src=“node_modules/spark-md5/spark-md5.js”></script>
- <script type=“text/javascript”>
- $(‘#file’).change(function () {
- let data = this.files[0];
- console.log(data)
- calculate(data, function (md5) {
- console.log(md5)//hash值
- })
- })
- function calculate(file, callBack) {
- let fileReader = new FileReader(),
- blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice,
- chunkSize = 2097152,
- // read in chunks of 2MB
- chunks = Math.ceil(file.size / chunkSize),
- currentChunk = 0,
- spark = new SparkMD5();
- fileReader.onload = function (e) {
- spark.appendBinary(e.target.result); // append binary string
- currentChunk++;
- if (currentChunk < chunks) {
- loadNext();
- }
- else {
- callBack(spark.end());
- }
- };
- function loadNext() {
- let start = currentChunk * chunkSize,
- end = start + chunkSize >= file.size ? file.size : start + chunkSize;
- fileReader.readAsBinaryString(blobSlice.call(file, start, end));
- };
- loadNext();
- }
- </script>
- </body>
- </html>
本文链接地址: js 获取文件 MD5