How to calculate hash file of md5 file using javascript

Is there a way to calculate the hash of an MD5 file before uploading to the server using Javascript?

+90
javascript md5
Apr 20 '09 at 13:32
source share
13 answers

Despite the JS implementation of the MD5 algorithm, older browsers, as a rule, cannot read files from the local file system .

I wrote this in 2009. So what about new browsers?

In a browser that supports FileAPI , you can * read the contents of the file - the user must select it either with the <input> element or with drag and drop. Starting in January 2013, here's how the main browsers stack up:

+87
Apr 20 '09 at 13:36
source share

I created a library that implements incremental md5 to handle large files efficiently. Basically you read the file in chunks (to save low memory) and hash it gradually. You have the main use and examples in readme.

Keep in mind that you need an HTML5 FileAPI file, so be sure to check it out. There is a complete example in the test folder.

https://github.com/satazor/SparkMD5

+27
Jan 17 2018-12-12T00:
source share

It’s pretty easy to calculate the MD5 hash using the MD5 function from CryptoJS and the HTML5 FileReader API . The following code snippet shows how you can read binary data and calculate the MD5 hash from an image that has been dragged into your browser:

 var holder = document.getElementById('holder'); holder.ondragover = function() { return false; }; holder.ondragend = function() { return false; }; holder.ondrop = function(event) { event.preventDefault(); var file = event.dataTransfer.files[0]; var reader = new FileReader(); reader.onload = function(event) { var binary = event.target.result; var md5 = CryptoJS.MD5(binary).toString() console.log(md5); }; reader.readAsBinaryString(file); }; 

I recommend adding CSS to see the drag area:

 #holder { border: 10px dashed #ccc; width: 300px; height: 300px; } #holder.hover { border: 10px dashed #333; } 

More information about the drag and drop function can be found here: File API and FileReader

I tested the sample in Google Chrome version 32.

+25
Jan 30 '14 at 1:36 on
source share

You need to use FileAPI. It is available in the latest versions of FF and Chrome, but not in IE9. Grab any JS md5 implementation suggested above. I tried this and abandoned it because JS was too slow (minutes on large image files). You can review it if someone rewrites MD5 using typed arrays.

The code looks something like this:

 HTML: <input type="file" id="file-dialog" multiple="true" accept="image/*"> JS (w JQuery) $("#file-dialog").change(function() { handleFiles(this.files); }); function handleFiles(files) { for (var i=0; i<files.length; i++) { var reader = new FileReader(); reader.onload = function() { var md5 = binl_md5(reader.result, reader.result.length); console.log("MD5 is " + md5); }; reader.onerror = function() { console.error("Could not read the file"); }; reader.readAsBinaryString(files.item(i)); } } 
+7
Apr 20 '11 at 3:32
source share

HTML5 + spark-md5 and Q

Assuming you are using a modern browser (which supports the HTML5 file API), here is how you calculate the MD5 Hash of a large file (it will calculate the hash on variable pieces)

 function calculateMD5Hash(file, bufferSize) { var def = Q.defer(); var fileReader = new FileReader(); var fileSlicer = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice; var hashAlgorithm = new SparkMD5(); var totalParts = Math.ceil(file.size / bufferSize); var currentPart = 0; var startTime = new Date().getTime(); fileReader.onload = function(e) { currentPart += 1; def.notify({ currentPart: currentPart, totalParts: totalParts }); var buffer = e.target.result; hashAlgorithm.appendBinary(buffer); if (currentPart < totalParts) { processNextPart(); return; } def.resolve({ hashResult: hashAlgorithm.end(), duration: new Date().getTime() - startTime }); }; fileReader.onerror = function(e) { def.reject(e); }; function processNextPart() { var start = currentPart * bufferSize; var end = Math.min(start + bufferSize, file.size); fileReader.readAsBinaryString(fileSlicer.call(file, start, end)); } processNextPart(); return def.promise; } function calculate() { var input = document.getElementById('file'); if (!input.files.length) { return; } var file = input.files[0]; var bufferSize = Math.pow(1024, 2) * 10; // 10MB calculateMD5Hash(file, bufferSize).then( function(result) { // Success console.log(result); }, function(err) { // There was an error, }, function(progress) { // We get notified of the progress as it is executed console.log(progress.currentPart, 'of', progress.totalParts, 'Total bytes:', progress.currentPart * bufferSize, 'of', progress.totalParts * bufferSize); }); } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/q.js/1.4.1/q.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/spark-md5/2.0.2/spark-md5.min.js"></script> <div> <input type="file" id="file"/> <input type="button" onclick="calculate();" value="Calculate" class="btn primary" /> </div> 
+7
Jul 18 '16 at 10:10
source share

Besides the inability to access the file system in JS, I would not trust the client checksum at all. So generating a checksum on the server is mandatory in any case. - Tomalak April 20, 2009 at 14:05

In most cases this is useless. You want MD5 to be computed on the client side, so that you can compare it with the code recounted on the server side and complete the download by mistake if they differ. I needed to do this in applications working with large scientific data files, where the key was to receive undamaged files. My cases were simple because users had MD5 already computed from their data analysis tools, so I just needed to ask them with a text box.

+4
Jun 04 2018-10-11T00:
source share

There are many options to get a hash of files. Usually the problem is that it is very slow to get a hash of large files.

I created a small library that receives a hash of files, with 64kb of the beginning of the file and 64kb of its end.

Real-time example: http://marcu87.github.com/hashme/ and library: https://github.com/marcu87/hashme

+3
Nov 29 '12 at 11:16
source share

There are several scripts on the Internet to create an MD5 hash file.

One of webtoolkit is good, http://www.webtoolkit.info/javascript-md5.html

Although, I do not think that he will have access to the local file system, since this access is limited.

+2
Apr 20 '09 at 13:36
source share

With current HTML5, it should be possible to calculate the hash file of the md5 binary file. But I think that the step before that would be to convert the commonplace BlobBuilder data to String, I am trying to take this step: but I could not be successful.

Here is the code I tried: Convert BlobBuilder to string, in HTML5 Javascript

0
Jul 31 '11 at 11:33
source share

I do not believe that in javascript there is a way to access the contents of a file upload. Therefore, you cannot watch the contents of a file to generate an MD5 sum.

However, you can send the file to the server, which can then send the MD5 amount back or send the contents of the file back. But this is a lot of work and probably not worth it for your purposes.

-one
Apr 20 '09 at 13:37
source share

Well it can be read files with HTML5 File API (see Blob interface). Not verified, but you could do it, maybe.

-one
Jan 20 '11 at 20:55
source share

In addition, you should never trust a customer. You just need to redo the hash after loading it.

-one
May 17 '12 at 19:51
source share

Without a plugin, you cannot access this binary data. You should study the use of the Flash application to download. I have colleagues who used SWFUpload , but I don’t know how to access the file itself. You may need to modify the SWF itself to allow this.

-3
Apr 21 '09 at 4:44
source share



All Articles