To calculate the MD5 value of a file in a web page, fortunately, this project only needs to be compatible with modern browsers, otherwise it will be killed.
In fact, md5 on files is very simple for the backend. For example, using Node.js, just the following lines of code will do:
But for browsers, if you can't use HTML5's file api, it's almost impossible for file md5. If you can not use the file API, please share it with me.
To md5 a file in a browser, the basic idea is to use the HTML5 FileReader interface to read the file to memory, then get the binary content of the file, and finally md5.
There are already people on Github who are researching this problem, and one of the best projects is js-spark-md5, which uses the world's fastest md5 algorithm.
For better code reuse, I encapsulated browser-md5-file on top of js-spark-md5, which makes it easier to use md5 file.
Project address: browser-md5-file:https://github.com/forsigner/browser-md5-file
It's very easy to use:
For detailed usage, please check the documentation on Github.
Regarding browser compatibility, due to the HTML5 API used, it can only be compatible with the following browsers:
- IE10+
- Firefox
- Chrome
- Safari
- Opera
Another point is that large MD5 files will perform poorly due to the need to read files to memory.
|