使用spark-md5.js计算文件的MD5

627 阅读1分钟

方法封装

/**
 * 计算文件MD5
 */
import SparkMD5 from 'spark-md5'

/**
 * 分片计算文件MD5
 * @param {*} file
 * @returns
 */
export const computedFileMD5 = (file = undefined) => {
  return new Promise((resolve, reject) => {
    if (!file) {
      reject(undefined)
    }
    const blobSlice =
      File.prototype.slice ||
      File.prototype.mozSlice ||
      File.prototype.webkitSlice
    const chunkSize = 2097152 * 50 // Read in chunks of 2MB * 50
    const chunks = Math.ceil(file.size / chunkSize)
    let currentChunk = 0
    const spark = new SparkMD5.ArrayBuffer()
    let fileReader = new FileReader()

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

      if (currentChunk < chunks) {
        loadNext()
      } else {
        // console.log('finished loading')
        const md5 = `${spark.end()}`
        // console.info('computed hash', md5) // Compute hash
        spark.reset()
        spark.destroy()
        fileReader = null
        resolve(md5)
      }
    }

    fileReader.onerror = function () {
      //   console.warn('oops, something went wrong.')
      // file read error
      reject(undefined)
    }

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

    loadNext()
  })
}

spark-md5