前端生成文件md5且计算进度

2 阅读1分钟

生成文件md5

方法

import SparkMD5 from 'spark-md5'
import { Message } from 'element-ui'
export default function getMd5(file, callback) {
  return new Promise((resolve) => {
    var blobSlice =
      File.prototype.slice ||
      File.prototype.mozSlice ||
      File.prototype.webkitSlice,
      chunkSize = 2097152, // Read in chunks of 2MB
      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++

      callback && callback(currentChunk, chunks)
      if (currentChunk < chunks) {
        loadNext()
      } else {
        const res = spark.end()
        resolve({ success: true, md5: res })
      }
    }

    // 读取分片失败时
    fileReader.onerror = function () {
      Message.error('文件读取出错!')
      resolve({ success: false })
    }

    // 开始读取文件分片
    function loadNext() {
      var start = currentChunk * chunkSize,
        end = start + chunkSize >= file.size ? file.size : start + chunkSize
      fileReader.readAsArrayBuffer(blobSlice.call(file, start, end))
    }

    loadNext()
  })
}

使用

        const { success, md5 } = await getMd5(file, (now, total) => {
          progress = Math.ceil((now / total) * 10)
        })