spark-md5获取文件md5唯一标识

一、获取文件md5唯一标识代码

完整代码地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import SparkMD5 from 'spark-md5'

// 获取文件MD5
export function getFileMD5(file, processFn) {
return new Promise((resolve, reject) => {
const fileReader = new FileReader() //分块读取文件对象

//file的slice方法,注意它的兼容性,在不同浏览器的写法不同
const blobSlice =
File.prototype.mozSlice ||
File.prototype.webkitSlice ||
File.prototype.slice

const chunkSize = 10 * 1024 * 1024 //分块大小,20M
const chunks = Math.ceil(file.size / chunkSize) //总块数
let currentChunk = 0 //当前块数
const spark = new SparkMD5() //获取MD5对象

fileReader.onload = e => {
//数据加载完毕事件
let binaryStr = ''
const bytes = new Uint8Array(e.target.result)
const length = bytes.byteLength
for (let i = 0; i < length; i++) {
binaryStr += String.fromCharCode(bytes[i]) //二进制转换字符串
}
spark.appendBinary(binaryStr)
currentChunk++
if (processFn) {
processFn(`${Math.ceil((currentChunk / chunks) * 100)}%`)
} else {
console.log('读取文件', `${Math.ceil((currentChunk / chunks) * 100)}%`)
}
if (currentChunk < chunks) {
loadNext() //读取下一块数据
} else {
const fileMd5 = spark.end() //得到文件MD5值
resolve(fileMd5)
}
}
fileReader.onerror = e => {
reject(e)
}

function loadNext() {
const start = currentChunk * chunkSize
const end = start + chunkSize >= file.size ? file.size : start + chunkSize
//根据开始和结束位置,切割文件
const b = blobSlice.call(file, start, end)
//readAsBinaryString ie浏览器不兼容此方法
//fileReader.readAsBinaryString(blobSlice.call(file, start, end));
fileReader.readAsArrayBuffer(b) //ie,chrome,firefox等主流浏览器兼容此方法
}
loadNext()
})
}

// 选择文件
export function selectFile() {
const id = 'kuan-upload-input'
let uploadInput = document.getElementById(id)
if (!uploadInput) {
uploadInput = document.createElement('input')
uploadInput.id = id
uploadInput.type = 'file'
uploadInput.style.display = 'none'
document.body.appendChild(uploadInput)
}
uploadInput.click()

return new Promise(resolve => {
uploadInput.onchange = () => {
const [file] = uploadInput.files
uploadInput.value = ''
resolve(file)
}
setTimeout(() => {}, 100)
})
}

export async function getFile({ needMD5 = true, readProcess } = {}) {
const file = await selectFile()
let md5 = ''
if (needMD5) {
md5 = await getFileMD5(file, readProcess)
}
return {
file,
md5
}
}

export default {
getFileMD5,
selectFile,
getFile
}

二、依赖库 spark-md5