oss-upload.js
Version:
The browser directly uploads files to oss
53 lines (41 loc) • 1.1 kB
JavaScript
import SparkMD5 from 'spark-md5';
let aborted = false
function fileMd5(file, md5Fn, progressFn){
let progress = 0
let currentChunk = 0
const blobSlice =
File.prototype.slice ||
File.prototype.mozSlice ||
File.prototype.webkitSlice
const chunkSize = 2097152
const chunks = Math.ceil(file.size / chunkSize)
const spark = new SparkMD5.ArrayBuffer()
const reader = new FileReader()
loadNext()
reader.onloadend = e => {
spark.append(e.target.result) // Append array buffer
currentChunk++
progress = currentChunk / chunks
if (progressFn && typeof progressFn === 'function') {
progressFn(progress)
}
if (aborted) {
md5Fn('aborted')
return
}
if (currentChunk < chunks) {
loadNext()
} else {
md5Fn(null, spark.end())
}
}
function loadNext() {
const start = currentChunk * chunkSize
const end = start + chunkSize >= file.size ? file.size : start + chunkSize
reader.readAsArrayBuffer(blobSlice.call(file, start, end))
}
}
function stopMd5(){
aborted = true
}
export {fileMd5,stopMd5}