演示地址:https://zhtt.gitee.io/angular-demo/great-ngform8/#/file/md5
前端断点续传时,往往需要根据文件生成md5值,一般实现是通过FileReader读取文件内容,然后根据内容使用md5工具类加密生成即可,示例如下:
readFile1(event: any): void {
const input = event.target;
const reader = new FileReader();
reader.onload = (() => {
if (reader.result) {
const md5 = md5utils.generator(reader.result);
}
});
reader.readAsText(file, 'utf-8');
}
但操作大文件时,使用不用当往往会引起内存溢出、读取不全等问题,同时本人还遇到了之前压缩好的zip文件,再次修改里面部分文件后,md5值一直不变。最终解决方案如下:
1、安装工具类
npm i great-jsutils
2、 导入工具类:JsUtilsApi
import {JsUtilsApi } from 'great-jsutils';
3、在组件中使用工具类
readFile(event: any) {
const input = event.target;
let file = input.files[0];
this.file.fileName = file.name;
JsUtilsApi.md5File(file).then(
(md5)=>{
this.file.fileMd5 = md5;
},
(error)=>{
console.log(error);
}
);
}