1、将上传的文件生成一个key(文件指纹):将文件内容生成一个指纹
<!--pdf文件校验-->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>
<!-- Apache Commons Codec for SHA-256 hash -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
工具类:
public static String GenerateFileFinger(File file) throws IOException, NoSuchAlgorithmException { //用于生成文件指纹
byte[] fileBytes = Files.readAllBytes(file.toPath());
// Create a MessageDigest instance for SHA-256
MessageDigest sha256Digest = MessageDigest.getInstance("SHA-256");
// Calculate the SHA-256 hash
byte[] hashBytes = sha256Digest.digest(fileBytes);
// Convert the hash bytes to hexadecimal
return DatatypeConverter.printHexBinary(hashBytes).toLowerCase();
}
将返回一个加密后的64位的加密字符串
由于前端传文件到后端会发生很多问题,比如说网络不稳定,数据乱码等会导致生成的指纹不一样,所以在前端同样生成这样的字符串在后端库里面进行匹配,如果有相同的就说明文件没有被更改过,否则就是被更改过,文件内容失效。
前端代码
import SHA256 from "crypto-js/sha256";
import WordArray from "crypto-js/lib-typedarrays"; // convert ArrayBuffer to WordArray
method:
handleFileUpload() {
const file = this.file;
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
const arrayBuffer = e.target.result;
const wordArray = WordArray.create(arrayBuffer);
const hash = SHA256(wordArray).toString();
// Set the file hash to the fileCode data property
this.fileCode = hash;
};
reader.readAsArrayBuffer(file);
}
},
这里前端需要下载相关的包 npm install crypto-js