hashFile.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // 此文件在worker环境下运行。
  2. importScripts('md5.js');
  3. var hashMe = function(file, callbackFunction) {
  4. var thisObj = this,
  5. _binStart = "",
  6. _binEnd = "",
  7. callback = "",
  8. fileManager1 = new FileReader,
  9. fileManager2 = new FileReader;
  10. thisObj.setBinAndHash = function(startOrEnd, binData) {
  11. switch (startOrEnd) {
  12. case 0:
  13. thisObj._binStart = binData;
  14. break;
  15. case 1:
  16. thisObj._binEnd = binData;
  17. }
  18. thisObj._binStart && thisObj._binEnd && thisObj.md5sum(thisObj._binStart, thisObj._binEnd)
  19. };
  20. thisObj.md5sum = function(start, end) {
  21. thisObj._hash = md5(start + end);
  22. callback(thisObj._hash);
  23. };
  24. thisObj.getHash = function() {
  25. return thisObj._hash;
  26. };
  27. thisObj.calculateHashOfFile = function(file) {
  28. fileManager1.onload = function(f) {
  29. thisObj.setBinAndHash(0, f.target.result);
  30. };
  31. fileManager2.onload = function(f) {
  32. thisObj.setBinAndHash(1, f.target.result);
  33. };
  34. var start = file.slice(0, 65536);
  35. var end = file.slice(file.size - 65536, file.size);
  36. fileManager1.readAsBinaryString(start);
  37. fileManager2.readAsBinaryString(end);
  38. };
  39. thisObj.calculateHashOfFile(file);
  40. callback = callbackFunction;
  41. };
  42. onmessage = function( e ) {
  43. var file = e.data;
  44. hashMe( file, function( ret ) {
  45. postMessage( ret );
  46. });
  47. }