文件进行MD5计算
Posted daniao11417
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文件进行MD5计算相关的知识,希望对你有一定的参考价值。
1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title></title> 7 <meta http-equiv="Pragma" content="no-cache" /> 8 </head> 9 10 <body> 11 <input type="file" id="audio" /> 12 <div id="handler_info"></div> 13 <div class="progressbar"></div> 14 </body> 15 <script src="js/spark-md5.js" type="text/javascript" charset="utf-8"></script> 16 <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> 17 <script type="text/javascript"> 18 $("#audio").on("change", function() { 19 let file = $("#audio")[0].files[0]; 20 if(!file) { 21 $("#audio_name").text(‘选择音频‘); 22 $(".progressbar").attr(‘value‘, 0); 23 $("#handler_info").html(‘‘); 24 filemd5 = ‘‘; 25 } else { 26 $("#audio_name").text(file.name); 27 get_filemd5sum(file) 28 } 29 }); 30 31 function get_filemd5sum(ofile) { 32 var file = ofile; 33 var tmp_md5; 34 var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice, 35 // file = this.files[0], 36 chunkSize = 8097152, // Read in chunks of 2MB 37 chunks = Math.ceil(file.size / chunkSize), 38 currentChunk = 0, 39 spark = new SparkMD5.ArrayBuffer(), 40 fileReader = new FileReader(); 41 42 fileReader.onload = function(e) { 43 // console.log(‘read chunk nr‘, currentChunk + 1, ‘of‘, chunks); 44 spark.append(e.target.result); // Append array buffer 45 currentChunk++; 46 var md5_progress = Math.floor((currentChunk / chunks) * 100); 47 console.log(file.name + " 正在处理,请稍等," + "已完成" + md5_progress + "%"); 48 var handler_info = document.getElementById("handler_info"); 49 var progressbar = document.getElementsByClassName("progressbar")[0]; 50 handler_info.innerHTML = file.name + " 正在处理,请稍等," + "已完成" + md5_progress + "%" 51 progressbar.value = md5_progress; 52 if(currentChunk < chunks) { 53 loadNext(); 54 } else { 55 tmp_md5 = spark.end(); 56 filemd5 = tmp_md5; 57 console.log(tmp_md5) 58 handler_info.innerHTML = file.name + "的MD5值是:" + tmp_md5; 59 } 60 }; 61 62 fileReader.onerror = function() { 63 console.warn(‘oops, something went wrong.‘); 64 }; 65 66 function loadNext() { 67 var start = currentChunk * chunkSize, 68 end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize; 69 fileReader.readAsArrayBuffer(blobSlice.call(file, start, end)); 70 } 71 loadNext(); 72 } 73 </script> 74 </html>
唯一需要注意的一点是,那个spark-md5.js的文件大家需要去下载。然后这里面的东西都是写好的。
以上是关于文件进行MD5计算的主要内容,如果未能解决你的问题,请参考以下文章