程序狗

  • {{ item.name }}
  • 首页
  • 归档
  • 笔记
  • 关于博主
  • 友情链接

前端计算文件MD5

  • Allen
  • 2017-02-14
  • 0

在上传文件的时候,为了校验文件的完整性或者实现断点续传,需要对比文件的MD5值。然而,前端怎么计算文件MD5值呢?查找相关资料之后,发现插件SparkMD5有较高的效率,故Mark之。

DEMO

好吧,先来一个demo,猛戳DEMO

基本用法

document.getElementById('file').addEventListener('change', function () {
    var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
        file = this.files[0],
        chunkSize = 2097152,
        chunks = Math.ceil(file.size / chunkSize),
        currentChunk = 0,
        spark = new SparkMD5.ArrayBuffer(),
        fileReader = new FileReader();

    fileReader.onload = function (e) {
        console.log('read chunk nr', currentChunk + 1, 'of', chunks);
        spark.append(e.target.result);
        currentChunk++;

        if (currentChunk < chunks) {
            loadNext();
        } else {
            console.log('finished loading');
            console.info('computed hash', spark.end());
        }
    };

    fileReader.onerror = function () {
        console.warn('oops, something went wrong.');
    };

    function loadNext() {
        var start = currentChunk * chunkSize,
            end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;

        fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
    }

    loadNext();
});

详细使用可以查看源码或更多的demo,传送门

© 2022 程序狗
Theme by Wing
粤ICP备15019690号-1