这应该很简单,但是我遇到了一些麻烦。
我想要从我的angular应用程序的本地"assets“目录中读取一个jpg文件,并计算图像文件的哈希值。
我在访问实际的文件时遇到了一些问题。通过查看各种资源,我提出了这一点,并安装了
const fs = require("fs");
const crypto = require("crypto");
const fileBuffer = fs.readFileSync(`assets/${`assetFile`}`)
const hashSum = crypto.createHash('sha256');
hashSum.update(fileBuffer);
const hex = hashSum.digest('hex');
console.log(hex);
return hex.toString();现在的问题是fs.readFileSync不能工作,如果我能用它来"fs“读取文件,我有点困惑。或者我应该使用https或其他什么,即使图像和代码或在同一台机器上?
发布于 2021-03-28 18:02:01
好的,由于fs只在后端可用,这里有一个使用FileReader的Angular-前端解决方案。
在UI中的某个位置放置一个按钮,以便打开一个文件对话框。该按钮应该调用此方法:
public loadFile(): void
{
const input = document.createElement('input');
input.type = 'file';
input.style.display = 'none';
input.onchange = (inputChangeEvent: any) =>
{
const file = inputChangeEvent.target.files[0];
const reader = new FileReader();
reader.addEventListener('loadend', () =>
{
const result = reader.result;
// here goes your additional code for hashing
});
reader.readAsArrayBuffer(file);
};
input.click();
}https://stackoverflow.com/questions/66838736
复制相似问题