0

I am using a react module called react-dropzone. When the user drops a file, it returns a File, which is a type of blob.

My goal is to find the sha-256 hash of this file. To do this I am trying to take the File, convert it into a buffer then feed the buffer to the crypto module. Here is the code I am using:

  handleOnDrop = file => {
      var fileReader = new FileReader();
      fileReader.onload = event => {
        this.externalScopeVariable = event.target.result;
      };
      const buffer = fileReader.readAsArrayBuffer(file);

      hash.update(buffer);
      console.log(hash.digest("hex"));
    });
  };

I am getting the error, TypeError: Cannot read property 'length' of undefined coming from the sha.js node module.

Any help on how to accomplish the task of successfully hashing the File is a huge help. Thanks

Hanley Soilsmith
  • 579
  • 2
  • 9
  • 27
  • 2
    Method `readAsArrayBuffer` is asynchronous and is not supposed to return value, so `buffer` will be always undefined. You need to move code below `readAsArrayBuffer` call into `onload` event handler. – kriplerm Jan 04 '19 at 22:00
  • I'm sorry, but the last sentence of your response is unclear to me, would you mind clarifying? Thank you – Hanley Soilsmith Jan 05 '19 at 02:14
  • 1
    Huh, that was even pretty clear to me, somebody who never works with JS. You need to call `update` in the `onload` handler. `buffer` is undefined, as `readAsArrayBuffer` isn't defined to return any result. – Maarten Bodewes Jan 05 '19 at 09:34
  • yes, thank you. If you are curious, answer is here>>> https://stackoverflow.com/questions/54050401/how-to-use-filereader-with-react-getting-a-strange-error – Hanley Soilsmith Jan 05 '19 at 16:55

0 Answers0