I am working with JavaScript to generate File HASH VALUE for unique file values. Kindly check the below code for the Hash Generation Mechanism Which works good.
<script type="text/javascript">
// Reference: https://code.google.com/p/crypto-js/#MD5
function handleFileSelect(evt)
{
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++)
{
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile)
{
return function(e)
{
var span = document.createElement('span');
var test = e.target.result;
//var hash = hex_md5(test);
var hash = CryptoJS.MD5(test);
var elem = document.getElementById("hashValue");
elem.value = hash;
};
})(f);
// Read in the image file as a data URL.
reader.readAsBinaryString(f);
}
}
document.getElementById('videoupload').addEventListener('change', handleFileSelect, false);
</script>
However I am facing problem when generating HASH VALUE for large files as in client side the browser Crashed.
Up-till 30MB the HASHING works well but if i try to upload larger than that the system crashes.
My Question is:
Can I generate HASH Value for part of file than reading the LARGE files and getting crashes? If yes, Can I know how to do that width 'FileReader';
Can I specify any amount of Byte such as 2000 Character of a file to generate HASH Value then generating for large files.
I hope the above two solution will work for larger and small files. Is there any other options?
Yes, you can do that and it is called Progressive Hashing.
There's an HTML5Rocks article on how one can use
File.slice
to pass a sliced file to theFileReader
:Full solution
I have combined both. The tricky part was to synchronize the file reading, because
FileReader.readAsArrayBuffer()
is asynchronous. I've written a smallseries
function which is modeled after theseries
function of async.js. It has to be done one after the other, because there is is no way to get to the internal state of the hashing function of CryptoJS.Additionally, CryptoJS doesn't understand what an
ArrayBuffer
is, so it has to be converted to its native data representation, which is the so-called WordArray:The other thing is that hashing is a synchronous operation where there is no
yield
to continue execution elsewhere. Because of this, the browser will freeze since JavaScript is single threaded. The solution is to use Web Workers to off-load the hashing to a different thread so that the UI thread keeps responsive.Web workers expect the script file in their constructors, so I used this solution by Rob W to have an inline script.
DEMO seems to work for big files, but it takes quite a lot of time. Maybe this can be improved using a faster MD5 implementation. It took around 23 minutes to hash a 3 GB file.
This answer of mine shows an example without webworkers for SHA-256.