0

This should be pretty simple, but I'm having some trouble.

I want to read a jpg file from the local "assets" directory in my angular app, and calculate the hash of the image file.

I am having some trouble though accessing the actual file. By looking at various resources, I came up with this, and installed

    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();

The right now problem is fs.readFileSync doesn't work, and I'm a little confused if I can use it to "fs" to read the file. Or should I be using https or something, even though the image and the code or on the same machine?

GGizmos
  • 3,443
  • 4
  • 27
  • 72

1 Answers1

0

Well, as fs is only available in the backend, here is an Angular-Frontend-solution using the FileReader.

Put a button somewhere in your UI in order to open a file dialog. The button is supposed to call this method:

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();
}
  • T/hanks for this, not quite sure it matches my needs. The method in question runs in the background, as an async triggered by the load event, and is meant to read a file that is in the src/app/assets directory and calculate its hash. Part of the function (not shown) is to check the hash hash against an outside source for validity. It seems like creating an input element is an indirect way to do that. Is that the only way to do it on the front end within Angular? – GGizmos Mar 28 '21 at 18:43
  • Yes, there is another way as long as the file is laying on the server side and not on your local disc: https://stackoverflow.com/questions/51682514/angular-how-to-download-a-file-from-httpclient –  Mar 28 '21 at 19:12