Search code examples
javascriptsha1checksumconsistent-hashing

How to checksum the file to be uploaded with javascript?


I want to checksum the files at browser side before uploading, then checksum and compare at server side to make sure the consistent. But how can I get the pure binary data of the file and checksum it? I tried the way below, but doesn't work:

let fileSelect = document.getElementById('file')
let files = fileSelect.files
let file = files[0]

var r = new FileReader();
r.onload = function(){ console.log(r.result); };
r.readAsArrayBuffer(file);
var file_sha1 = sha1(r.result)

Solution

  • The library you are using seems to support string input only. Find a library support binary input. Eg. js-sha1. And you should hash it in the callback.

    var reader = new FileReader();
    reader.onload = function (event) {
      var file_sha1 = sha1(event.target.result)
    };
    reader.readAsArrayBuffer(file);