在浏览器中使用js-spark-md5计算文件的MD5
最近开发一个视频系统,用户需要把文件上传到服务器。服务器再上传到转码服务器,编码为m3u8格式。我觉得客户端可以直接上传到转码服务器。对转码服务器设置了跨域后,客户端可以直接上传视频文件,但是上传接口需要文件的MD5值,网上找了一个口碑极好的MD5库 js-spark-md5(据说性能是最牛逼的)
https://github.com/satazor/js-spark-md5
官方的Demo
document.getElementById('file').addEventListener('change', function () {
var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
file = this.files[0],
chunkSize = 2097152, // Read in chunks of 2MB
chunks = Math.ceil(file.size / chunkSize),
currentChunk = 0,
spark = new SparkMD5.ArrayBuffer(),
fileReader = new FileReader();
fileReader.onload = function (e) {
console.log('read chunk nr', currentChunk + 1, 'of', chunks);
spark.append(e.target.result); // Append array buffer
currentChunk++;
if (currentChunk < chunks) {
loadNext();
} else {
console.log('finished loading');
console.info('computed hash', spark.end()); // Compute hash
}
};
fileReader.onerror = function () {
console.warn('oops, something went wrong.')