赞
踩
生成md5
注意:最好限制文件大小,否则时间很长,用户观感很可能不好
const getMd5FromSliceFile = (file: any) => {
return new Promise((resolve, reject) => {
const filePrototype: any = File.prototype;
let blobSlice = filePrototype.slice || filePrototype.mozSlice || filePrototype.webkitSlice;
const chunkSize = 2 * Math.pow(1024, 2); // 每片2m
let chunks = Math.ceil(file.size / chunkSize); // 片数
let currentChunk = 0;
const fileReader = new FileReader();
const spark = new SparkMD5.ArrayBuffer();
const loadFile = () => {
const start = chunkSize * currentChunk;
const end = start + chunkSize > file.size ? file.size : start + chunkSize;
if (start > file.size - 1) return;
const slice = blobSlice.call(file, start, end);
fileReader.readAsArrayBuffer(slice);
}
loadFile();
fileReader.onload = (e: any) => {
spark.append(e.target.result);
currentChunk++;
if (currentChunk < chunks) {
loadFile()
} else {
const md5 = spark.end();
spark.destroy();
console.log('finish loading, getMd5FromSliceFile', md5, file.name, (Date.now() - time1) / 1000 + 's')
return resolve(md5);
}
};
fileReader.onerror = (err: any) => {
return reject(err);
}
});
}
对文件进行切片
每次切片接口调用前获取该份切片
- const splitFile = (file: Blob, pieceByte: number, index: number) => {
- const chunkSum = Math.ceil(_.get(file, "size") / pieceByte); // 切片总数
- const chunkSize = Math.ceil(_.get(file, "size") / chunkSum); // 除以切片总数求得平均每片size多大
- const { size, type } = file;
- const filePrototype = File.prototype;
- let blobSlice = filePrototype.slice || _.get(filePrototype, 'mozSlice') || _.get(filePrototype, 'webkitSlice');
- if (size > pieceByte) {
- let start = index * chunkSize; // 切片开始位置
- let end = start + chunkSize; // 切片结束位置
- console.log(start, end, "start---end");
- const file1 = _.get(file, "originFileObj");
- let item:any = null
- try {
- item = blobSlice.call(file, start, end, type); // 切割的文件
- } catch (error) {
- // 如果file没有slice方法, 就从file.originFileObj找
- item = blobSlice.call(file1, start, end, type); // 切割的文件
- }
-
- return item;
- }
- return file;
- };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。