Skip to content

Instantly share code, notes, and snippets.

@JWally
Last active October 29, 2024 11:23
Show Gist options
  • Select an option

  • Save JWally/4403220 to your computer and use it in GitHub Desktop.

Select an option

Save JWally/4403220 to your computer and use it in GitHub Desktop.
Simple Method to Calculate the Hash of a file in Javascript using HTML5 API
//Event Listener tied to the file input field
document.getElementById('attachment').addEventListener('change', eventHandler, false)
/**
*Description: Simple method to handle an event
*and fire off a function
**/
function eventHandler(evt){
var file = evt.target.files[0];
fileHash( file, md5, function(x){
console.log( x );
});
}
/**
*Description: The actual function to calculate the hash
*Arguments:
*file: a file from a file input load event
*hasher: hashing algorithm
*callback: function that does something with the hash
**/
function fileHash( file, hasher, callback ){
//Instantiate a reader
var reader = new FileReader();
//What to do when we gets data?
reader.onload = function( e ){
var hash = hasher(e.target.result);
callback( hash );
}
reader.readAsBinaryString( file );
}
@rguariento
Copy link
Copy Markdown

I'm getting "md5 is not defined". What is md5 in your code? Thank you.
(I'm testing in raw html)

@emersiljr
Copy link
Copy Markdown

I'm getting "md5 is not defined". What is md5 in your code? Thank you. (I'm testing in raw html)
See this one, it worked for me:
https://techoverflow.net/2021/11/26/how-to-compute-sha-hash-of-local-file-in-javascript-using-subtlecrypto-api/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment