计算文件的MD5

使用spark-md5

npm install spark-md5 -S

因项目需要,这里使用了Typescript,并将获得文件MD5的方法封装成一个函数,得到的MD5以Promise对象的形式暴露出去

核心代码

fileMD5.ts文件

import SparkMD5 from 'spark-md5'

class FileMD5 {
  //计算文件MD5
  public computeMD5(file){
    return new Promise(function(resolve, reject){
      let blobSlice = File.prototype.slice || (File.prototype as any).mozSlice || (File.prototype as any).webkitSlice;
      let chunkSize = 2097152; //2MB
      let chunks = Math.ceil(file.size / chunkSize);  //分块数
      let currentChunk = 0;  //当前块
      let spark = new SparkMD5.ArrayBuffer();
      let fileReader = new FileReader();

      fileReader.onload = (e) => {
        spark.append((e.target as any).result);   // Append array buffer

        currentChunk++;
        if(currentChunk < chunks){
           console.log(`第${currentChunk}分片解析完成, 开始第${currentChunk +1} / ${chunks}分片解析`);
          loadNext();
        }else{
           console.log('finished loading');
          let md5=spark.end();  //得到md5
           console.log(`文件名:${file.name}\nMD5:${md5}\n分片:${chunks}`);
          spark.destroy(); //释放缓存
          file.uniqueIdentifier = md5; //将文件md5赋值给文件唯一标识
          resolve(file);
        }
      };

      fileReader.onerror = () => {
        reject('oops, something went wrong.');
      };

      let loadNext = () => {
        let start = currentChunk*chunkSize;
        let end=((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
        fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
      };
      loadNext();
    })
    
  }
}

export const getFileMD5=new FileMD5();

vue文件

import {getFileMD5} from 'fileMD5.js文件的相对路径'
var fileMD5=getFileMD5.computeMD5(file);

fileMD5.then(res => {
    console.log(res);
})
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页